Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Support selectable local OCR providers https://github.com/siyuan-note/siyuan/issues/19984

Daniel1f00701552fd
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.yml
index 79a3a889b2..442e4dfd4f 100644
--- a/.github/workflows/cd.yml
+++ b/.github/workflows/cd.yml
@@ -161,11 +161,16 @@ jobs:
run: |
sudo apt-get update
sudo apt-get install -y strace
+ - name: Prepare native OCR verification resources
+ run: python3 scripts/prepare-ocr.py --runtime linux-amd64 --build-worker
- name: Test all kernel packages
# 测试失败只记录结果,不阻塞后续发布构建。
continue-on-error: true
run: go test -tags "fts5 sqlcipher" ./... -count=1
working-directory: kernel
+ env:
+ SIYUAN_OCR_TEST_ASSETS: ${{ github.workspace }}/app/stage/ocr/models
+ SIYUAN_OCR_TEST_LIBRARY: ${{ github.workspace }}/app/stage/ocr/runtime/linux-amd64/libonnxruntime.so
- name: Test path fixtures with custom temporary directories
# 测试失败只记录结果,不阻塞后续发布构建。
continue-on-error: true
@@ -197,6 +202,8 @@ jobs:
continue-on-error: true
run: pnpm test
working-directory: app
+ - name: Test OCR resource preparation
+ run: python -m unittest discover -s scripts -p "test_prepare_ocr.py"
build:
runs-on: ${{ matrix.config.os }}
@@ -662,7 +669,8 @@ jobs:
${{ github.workspace }}/siyuan-android/app/libs/kernel.aar
cd ${{ github.workspace }}/go/src/github.com/${{ github.repository }}/app
node scripts/trimChangelogs.js
- zip -r app.zip appearance guide stage $([ -d changelogs ] && echo changelogs)
+ python3 ../scripts/prepare-ocr.py
+ zip -r app.zip appearance guide stage $([ -d changelogs ] && echo changelogs) -x 'stage/ocr/runtime/*'
zip -j app.zip ../LICENSE ../THIRD_PARTY_NOTICES.md
mkdir -p ${{ github.workspace }}/siyuan-android/app/src/main/assets
cp app.zip ${{ github.workspace }}/siyuan-android/app/src/main/assets/app.zip
diff --git a/.gitignore b/.gitignore
index 8844736075..2a1c553531 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,3 +50,6 @@ muslbin/
# Workflows
**/__pycache__
+# OCR 模型和运行时由固定版本、校验摘要的发布准备脚本生成
+/app/stage/ocr/models/
+/app/stage/ocr/runtime/
diff --git a/Dockerfile b/Dockerfile
index e92ac5216b..b42bdacdfb 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -14,8 +14,12 @@ pnpm install --silent
EORUN
ADD app/ .
+ADD scripts/prepare-ocr.py scripts/ocr-assets.json /scripts/
RUN <<EORUN
#!/bin/bash -e
+apt-get update
+apt-get install -y --no-install-recommends python3
+python3 /scripts/prepare-ocr.py
pnpm run build
node scripts/trimChangelogs.js
mkdir /artifacts
@@ -41,10 +45,26 @@ ADD kernel/ .
RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg \
go build -tags "fts5 sqlcipher" -ldflags "-s -w"
+FROM go-build AS ocr-build
+ARG TARGETARCH
+# 容器保留 Alpine 基础镜像,使用 musl 构建原生运行时和识别辅助进程。
+RUN apk add --no-cache bash cmake make g++ git python3 py3-pip py3-packaging linux-headers
+RUN git clone --no-checkout https://github.com/microsoft/onnxruntime /onnxruntime \
+ && cd /onnxruntime \
+ && git checkout 3a728b75062256951b6e19ce718907cf1a1d4cf0 \
+ && git submodule update --init --recursive
+RUN python3 /onnxruntime/tools/ci_build/build.py --build_dir /onnxruntime/build \
+ --config Release --update --build --parallel 2 --build_shared_lib \
+ --skip_tests --allow_running_as_root --compile_no_warning_as_error
+RUN mkdir -p /ocr/linux-${TARGETARCH} \
+ && cp /onnxruntime/build/Release/libonnxruntime.so.1.24.3 /ocr/linux-${TARGETARCH}/libonnxruntime.so \
+ && cp /onnxruntime/LICENSE /onnxruntime/ThirdPartyNotices.txt /ocr/linux-${TARGETARCH}/ \
+ && go build -trimpath -ldflags "-s -w" -o /ocr/linux-${TARGETARCH}/siyuan-ocr ./ocr/cmd/ocr-worker
+
FROM alpine:latest
LABEL maintainer="Liang Ding<[email protected]>"
-RUN apk add --no-cache ca-certificates tzdata su-exec
+RUN apk add --no-cache ca-certificates tzdata su-exec libstdc++
ENV TZ=Asia/Shanghai
ENV HOME=/home/siyuan
@@ -54,6 +74,7 @@ EXPOSE 6806
WORKDIR /opt/siyuan/
COPY --from=go-build --chmod=755 /kernel/kernel /kernel/entrypoint.sh .
COPY --from=node-build /artifacts .
+COPY --from=ocr-build /ocr stage/ocr/runtime
COPY LICENSE THIRD_PARTY_NOTICES.md .
ENTRYPOINT ["/opt/siyuan/entrypoint.sh"]
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 9fb9ffe115..b424c4f4c3 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -21,6 +21,8 @@ The component list is informational and does not replace the license terms. Copy
| Component | Version | License | Source | Distribution |
|---|---|---|---|---|
| Electron | 42.7.1 | MIT | [upstream](https://github.com/electron/electron) | Desktop runtime; Electron also ships LICENSES.chromium.html for Chromium and its dependencies |
+| ONNX Runtime | 1.24.3 (Windows, Linux, Apple Silicon, Android, HarmonyOS), 1.23.2 (Intel macOS), 1.24.2 (iOS) | MIT | [upstream](https://github.com/microsoft/onnxruntime) | Native CPU OCR runtime; license and dependency notices in app/stage/ocr/ONNXRUNTIME-LICENSE and ONNXRUNTIME-THIRD-PARTY-NOTICES.txt; desktop libraries also include their corresponding notices |
+| PaddleOCR PP-OCRv6 Tiny and Small ONNX models | Pinned revisions in scripts/ocr-assets.json | Apache-2.0 | [official models](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | app/stage/ocr/models/; license text in app/stage/ocr/PADDLEOCR-LICENSE |
| DOMPurify | 3.3.3 | Apache-2.0 OR MPL-2.0 | [upstream](https://github.com/cure53/DOMPurify) | app/stage/protyle/js/protyle-html.js |
| html-to-image | 1.11.13 | MIT | [upstream](https://github.com/bubkoo/html-to-image) | app/stage/protyle/js/html-to-image.min.js |
| modern-screenshot | 4.6.6 | MIT | [upstream](https://github.com/qq15725/modern-screenshot) | app/stage/protyle/js/modern-screenshot.min.js |
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 240682dca7..bd0f6ddb5d 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "موفّر OCR",
+ "ocrProviderTip": "التعرّف دون اتصال في النواة المحلية؛ ثبّت Tesseract بشكل منفصل؛ لا يتم التبديل تلقائيًا عند عدم التوفر",
+ "ocrAuto": "OCR تلقائي",
+ "ocrAutoTip": "معالجة صور دفاتر الملاحظات العادية التي ليس لها نتيجة OCR بعد",
+ "ocrModel": "نموذج OCR",
+ "ocrModelTip": "Tiny وSmall مضمّنان؛ يحتفظ التبديل بالنتائج الحالية؛ أعد تشغيل OCR من قائمة الصورة",
+ "ocrImportModels": "استيراد نماذج OCR",
+ "ocrImportModelsTip": "اختر ملفات ONNX المتوافقة للكشف والتعرّف في PP-OCRv6 وملفات inference.yml الخاصة بها؛ تتزامن الملفات المستوردة مع مساحة العمل",
+ "ocrDetector": "نموذج الكشف",
+ "ocrRecognizer": "نموذج التعرّف",
+ "ocrUnavailable": "غير متوفر",
"pinWindow": "إبقاء النافذة في المقدمة",
"unpinWindow": "إلغاء إبقاء النافذة في المقدمة",
"settingsWindowMode": "مكان فتح الإعدادات",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index e8b7a09cef..7a55ecee74 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR-Anbieter",
+ "ocrProviderTip": "Offline-Erkennung im lokalen Kernel; Tesseract separat installieren; kein automatischer Wechsel bei Nichtverfügbarkeit",
+ "ocrAuto": "Automatische OCR",
+ "ocrAutoTip": "Bilder normaler Notizbücher ohne vorhandenes OCR-Ergebnis verarbeiten",
+ "ocrModel": "OCR-Modell",
+ "ocrModelTip": "Tiny und Small sind integriert; ein Wechsel behält Ergebnisse bei; OCR im Bildmenü erneut ausführen",
+ "ocrImportModels": "OCR-Modelle importieren",
+ "ocrImportModelsTip": "Kompatible PP-OCRv6-ONNX-Dateien für Erkennung und Texterfassung sowie deren inference.yml auswählen; importierte Dateien werden mit dem Arbeitsbereich synchronisiert",
+ "ocrDetector": "Erkennungsmodell",
+ "ocrRecognizer": "Texterfassungsmodell",
+ "ocrUnavailable": "Nicht verfügbar",
"pinWindow": "Fenster im Vordergrund halten",
"unpinWindow": "Fenster nicht mehr im Vordergrund halten",
"settingsWindowMode": "Einstellungen öffnen in",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 29c162bd8a..5677f7f607 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR provider",
+ "ocrProviderTip": "Recognize offline in the local kernel; install Tesseract separately; unavailable providers do not fall back automatically",
+ "ocrAuto": "Automatic OCR",
+ "ocrAutoTip": "Process ordinary notebook images that have no OCR result yet",
+ "ocrModel": "OCR model",
+ "ocrModelTip": "Tiny and Small are built in; switching preserves existing results; rerun OCR from the image menu",
+ "ocrImportModels": "Import OCR models",
+ "ocrImportModelsTip": "Select compatible PP-OCRv6 detection and recognition ONNX files and their inference.yml files; imported files sync with the workspace",
+ "ocrDetector": "Detection model",
+ "ocrRecognizer": "Recognition model",
+ "ocrUnavailable": "Unavailable",
"pinWindow": "Keep window on top",
"unpinWindow": "Stop keeping window on top",
"settingsWindowMode": "Open settings in",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 4d81f7855a..976b264740 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Proveedor de OCR",
+ "ocrProviderTip": "Reconocimiento sin conexión en el núcleo local; instale Tesseract por separado; no se cambia automáticamente si no está disponible",
+ "ocrAuto": "OCR automático",
+ "ocrAutoTip": "Procesar imágenes de cuadernos normales que aún no tienen resultados de OCR",
+ "ocrModel": "Modelo de OCR",
+ "ocrModelTip": "Tiny y Small están integrados; cambiar conserva los resultados existentes; repita el OCR desde el menú de la imagen",
+ "ocrImportModels": "Importar modelos de OCR",
+ "ocrImportModelsTip": "Seleccione archivos ONNX compatibles de detección y reconocimiento PP-OCRv6 y sus archivos inference.yml; los archivos importados se sincronizan con el espacio de trabajo",
+ "ocrDetector": "Modelo de detección",
+ "ocrRecognizer": "Modelo de reconocimiento",
+ "ocrUnavailable": "No disponible",
"pinWindow": "Mantener ventana encima",
"unpinWindow": "Dejar de mantener ventana encima",
"settingsWindowMode": "Abrir ajustes en",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index acf9170272..623e5ba63b 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Fournisseur OCR",
+ "ocrProviderTip": "Reconnaissance hors ligne dans le noyau local ; installez Tesseract séparément ; aucun changement automatique en cas d’indisponibilité",
+ "ocrAuto": "OCR automatique",
+ "ocrAutoTip": "Traiter les images des carnets ordinaires sans résultat OCR existant",
+ "ocrModel": "Modèle OCR",
+ "ocrModelTip": "Tiny et Small sont intégrés ; le changement conserve les résultats existants ; relancez l’OCR depuis le menu de l’image",
+ "ocrImportModels": "Importer des modèles OCR",
+ "ocrImportModelsTip": "Sélectionnez les fichiers ONNX compatibles de détection et de reconnaissance PP-OCRv6 et leurs fichiers inference.yml ; les fichiers importés sont synchronisés avec l’espace de travail",
+ "ocrDetector": "Modèle de détection",
+ "ocrRecognizer": "Modèle de reconnaissance",
+ "ocrUnavailable": "Indisponible",
"pinWindow": "Garder la fenêtre au premier plan",
"unpinWindow": "Ne plus garder la fenêtre au premier plan",
"settingsWindowMode": "Ouvrir les paramètres dans",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index cb1fba39bb..2b18def405 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "ספק OCR",
+ "ocrProviderTip": "זיהוי לא מקוון בליבה המקומית; יש להתקין את Tesseract בנפרד; אין מעבר אוטומטי כשהספק אינו זמין",
+ "ocrAuto": "OCR אוטומטי",
+ "ocrAutoTip": "עיבוד תמונות במחברות רגילות שעדיין אין להן תוצאת OCR",
+ "ocrModel": "מודל OCR",
+ "ocrModelTip": "Tiny ו-Small מובנים; החלפה שומרת על התוצאות הקיימות; אפשר להריץ OCR שוב מתפריט התמונה",
+ "ocrImportModels": "ייבוא מודלי OCR",
+ "ocrImportModelsTip": "בחרו קובצי ONNX תואמים לזיהוי אזורים וטקסט של PP-OCRv6 ואת קובצי inference.yml שלהם; הקבצים המיובאים מסונכרנים עם סביבת העבודה",
+ "ocrDetector": "מודל זיהוי אזורים",
+ "ocrRecognizer": "מודל זיהוי טקסט",
+ "ocrUnavailable": "לא זמין",
"pinWindow": "השארת החלון תמיד מעל",
"unpinWindow": "ביטול השארת החלון תמיד מעל",
"settingsWindowMode": "פתיחת ההגדרות ב",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index d492def5c1..f9d3dfdab7 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR प्रदाता",
+ "ocrProviderTip": "स्थानीय कर्नेल में ऑफ़लाइन पहचान; Tesseract अलग से स्थापित करें; अनुपलब्ध होने पर प्रदाता अपने आप नहीं बदलेगा",
+ "ocrAuto": "स्वचालित OCR",
+ "ocrAutoTip": "सामान्य नोटबुक की उन छवियों को संसाधित करें जिनका OCR परिणाम अभी नहीं है",
+ "ocrModel": "OCR मॉडल",
+ "ocrModelTip": "Tiny और Small अंतर्निहित हैं; बदलने पर मौजूदा परिणाम सुरक्षित रहते हैं; छवि मेनू से OCR दोबारा चलाएँ",
+ "ocrImportModels": "OCR मॉडल आयात करें",
+ "ocrImportModelsTip": "संगत PP-OCRv6 पहचान और पाठ-पठन ONNX फ़ाइलें तथा उनकी inference.yml फ़ाइलें चुनें; आयातित फ़ाइलें कार्यक्षेत्र के साथ सिंक होती हैं",
+ "ocrDetector": "पहचान मॉडल",
+ "ocrRecognizer": "पाठ-पठन मॉडल",
+ "ocrUnavailable": "अनुपलब्ध",
"pinWindow": "विंडो को सबसे ऊपर रखें",
"unpinWindow": "विंडो को सबसे ऊपर रखना बंद करें",
"settingsWindowMode": "सेटिंग खोलने का स्थान",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 272fa6740c..dc73a34dc8 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Penyedia OCR",
+ "ocrProviderTip": "Pengenalan luring di kernel lokal; pasang Tesseract secara terpisah; tidak berpindah otomatis saat tidak tersedia",
+ "ocrAuto": "OCR otomatis",
+ "ocrAutoTip": "Proses gambar buku catatan biasa yang belum memiliki hasil OCR",
+ "ocrModel": "Model OCR",
+ "ocrModelTip": "Tiny dan Small sudah disertakan; pergantian mempertahankan hasil yang ada; ulangi OCR dari menu gambar",
+ "ocrImportModels": "Impor model OCR",
+ "ocrImportModelsTip": "Pilih berkas ONNX deteksi dan pengenalan PP-OCRv6 yang kompatibel beserta inference.yml masing-masing; berkas impor disinkronkan dengan ruang kerja",
+ "ocrDetector": "Model deteksi",
+ "ocrRecognizer": "Model pengenalan",
+ "ocrUnavailable": "Tidak tersedia",
"pinWindow": "Pertahankan jendela di atas",
"unpinWindow": "Berhenti mempertahankan jendela di atas",
"settingsWindowMode": "Buka pengaturan di",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 0d2a1ccfa8..e48d193467 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Fornitore OCR",
+ "ocrProviderTip": "Riconoscimento offline nel kernel locale; installare Tesseract separatamente; nessun cambio automatico se non disponibile",
+ "ocrAuto": "OCR automatico",
+ "ocrAutoTip": "Elabora le immagini dei quaderni normali che non hanno ancora risultati OCR",
+ "ocrModel": "Modello OCR",
+ "ocrModelTip": "Tiny e Small sono integrati; il cambio conserva i risultati esistenti; ripetere l’OCR dal menu dell’immagine",
+ "ocrImportModels": "Importa modelli OCR",
+ "ocrImportModelsTip": "Selezionare i file ONNX compatibili di rilevamento e riconoscimento PP-OCRv6 e i relativi inference.yml; i file importati vengono sincronizzati con lo spazio di lavoro",
+ "ocrDetector": "Modello di rilevamento",
+ "ocrRecognizer": "Modello di riconoscimento",
+ "ocrUnavailable": "Non disponibile",
"pinWindow": "Mantieni la finestra in primo piano",
"unpinWindow": "Non mantenere più la finestra in primo piano",
"settingsWindowMode": "Apri le impostazioni in",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 315af0ccb5..002d5bf584 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR プロバイダー",
+ "ocrProviderTip": "ローカルカーネルでオフライン認識します。Tesseract は別途インストールが必要です。利用できない場合も自動切り替えは行いません",
+ "ocrAuto": "自動 OCR",
+ "ocrAutoTip": "OCR 結果がまだない通常のノートブックの画像を処理します",
+ "ocrModel": "OCR モデル",
+ "ocrModelTip": "Tiny と Small は内蔵されています。切り替えても既存の結果は保持され、画像メニューから再認識できます",
+ "ocrImportModels": "OCR モデルをインポート",
+ "ocrImportModelsTip": "対応する PP-OCRv6 の検出・認識 ONNX ファイルとそれぞれの inference.yml を選択します。インポートしたファイルはワークスペースと同期されます",
+ "ocrDetector": "検出モデル",
+ "ocrRecognizer": "認識モデル",
+ "ocrUnavailable": "利用不可",
"pinWindow": "ウィンドウを最前面に表示",
"unpinWindow": "ウィンドウの最前面表示を解除",
"settingsWindowMode": "設定を開く場所",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index e2c1d15694..a4c6429b12 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR 제공자",
+ "ocrProviderTip": "로컬 커널에서 오프라인으로 인식합니다. Tesseract는 별도로 설치해야 하며, 사용할 수 없어도 자동으로 전환하지 않습니다",
+ "ocrAuto": "자동 OCR",
+ "ocrAutoTip": "OCR 결과가 없는 일반 노트북 이미지만 처리합니다",
+ "ocrModel": "OCR 모델",
+ "ocrModelTip": "Tiny와 Small이 내장되어 있습니다. 변경해도 기존 결과는 유지되며 이미지 메뉴에서 다시 인식할 수 있습니다",
+ "ocrImportModels": "OCR 모델 가져오기",
+ "ocrImportModelsTip": "호환되는 PP-OCRv6 감지 및 인식 ONNX 파일과 각각의 inference.yml을 선택하세요. 가져온 파일은 작업 공간과 동기화됩니다",
+ "ocrDetector": "감지 모델",
+ "ocrRecognizer": "인식 모델",
+ "ocrUnavailable": "사용 불가",
"pinWindow": "창을 항상 위에 표시",
"unpinWindow": "창의 항상 위 표시 해제",
"settingsWindowMode": "설정을 열 위치",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 47107816a8..b8826c7a18 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR-provider",
+ "ocrProviderTip": "Offline herkennen in de lokale kernel; installeer Tesseract afzonderlijk; geen automatische wissel bij onbeschikbaarheid",
+ "ocrAuto": "Automatische OCR",
+ "ocrAutoTip": "Afbeeldingen in gewone notitieboeken zonder bestaand OCR-resultaat verwerken",
+ "ocrModel": "OCR-model",
+ "ocrModelTip": "Tiny en Small zijn ingebouwd; wisselen behoudt bestaande resultaten; voer OCR opnieuw uit via het afbeeldingsmenu",
+ "ocrImportModels": "OCR-modellen importeren",
+ "ocrImportModelsTip": "Selecteer compatibele PP-OCRv6-ONNX-bestanden voor detectie en herkenning en hun inference.yml-bestanden; geïmporteerde bestanden synchroniseren met de werkruimte",
+ "ocrDetector": "Detectiemodel",
+ "ocrRecognizer": "Herkenningsmodel",
+ "ocrUnavailable": "Niet beschikbaar",
"pinWindow": "Venster bovenaan houden",
"unpinWindow": "Venster niet meer bovenaan houden",
"settingsWindowMode": "Instellingen openen in",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 7d01b04d59..f6875d2403 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Dostawca OCR",
+ "ocrProviderTip": "Rozpoznawanie offline w lokalnym jądrze; zainstaluj Tesseract oddzielnie; brak automatycznej zmiany w razie niedostępności",
+ "ocrAuto": "Automatyczny OCR",
+ "ocrAutoTip": "Przetwarzaj obrazy w zwykłych notatnikach, które nie mają jeszcze wyniku OCR",
+ "ocrModel": "Model OCR",
+ "ocrModelTip": "Tiny i Small są wbudowane; zmiana zachowuje istniejące wyniki; ponów OCR z menu obrazu",
+ "ocrImportModels": "Importuj modele OCR",
+ "ocrImportModelsTip": "Wybierz zgodne pliki ONNX wykrywania i rozpoznawania PP-OCRv6 oraz ich pliki inference.yml; importowane pliki są synchronizowane z obszarem roboczym",
+ "ocrDetector": "Model wykrywania",
+ "ocrRecognizer": "Model rozpoznawania",
+ "ocrUnavailable": "Niedostępny",
"pinWindow": "Utrzymuj okno na wierzchu",
"unpinWindow": "Nie utrzymuj okna na wierzchu",
"settingsWindowMode": "Otwieraj ustawienia w",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index a84dcd1c67..0e6961ba4c 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Provedor de OCR",
+ "ocrProviderTip": "Reconhecimento offline no núcleo local; instale o Tesseract separadamente; não há troca automática se estiver indisponível",
+ "ocrAuto": "OCR automático",
+ "ocrAutoTip": "Processar imagens de cadernos comuns que ainda não possuem resultado de OCR",
+ "ocrModel": "Modelo de OCR",
+ "ocrModelTip": "Tiny e Small são integrados; a troca preserva os resultados existentes; repita o OCR pelo menu da imagem",
+ "ocrImportModels": "Importar modelos de OCR",
+ "ocrImportModelsTip": "Selecione arquivos ONNX compatíveis de detecção e reconhecimento PP-OCRv6 e seus arquivos inference.yml; os arquivos importados são sincronizados com o espaço de trabalho",
+ "ocrDetector": "Modelo de detecção",
+ "ocrRecognizer": "Modelo de reconhecimento",
+ "ocrUnavailable": "Indisponível",
"pinWindow": "Manter janela no topo",
"unpinWindow": "Deixar de manter janela no topo",
"settingsWindowMode": "Abrir configurações em",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 7e1f4b2393..51bf76e7db 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Провайдер OCR",
+ "ocrProviderTip": "Распознавание офлайн в локальном ядре; установите Tesseract отдельно; автоматического переключения при недоступности нет",
+ "ocrAuto": "Автоматический OCR",
+ "ocrAutoTip": "Обрабатывать изображения обычных блокнотов, для которых ещё нет результата OCR",
+ "ocrModel": "Модель OCR",
+ "ocrModelTip": "Tiny и Small встроены; смена сохраняет существующие результаты; повторите OCR из меню изображения",
+ "ocrImportModels": "Импорт моделей OCR",
+ "ocrImportModelsTip": "Выберите совместимые ONNX-файлы обнаружения и распознавания PP-OCRv6 и соответствующие inference.yml; импортированные файлы синхронизируются с рабочим пространством",
+ "ocrDetector": "Модель обнаружения",
+ "ocrRecognizer": "Модель распознавания",
+ "ocrUnavailable": "Недоступен",
"pinWindow": "Поверх всех окон",
"unpinWindow": "Отменить отображение поверх всех окон",
"settingsWindowMode": "Где открывать настройки",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 0bc71f6fa6..1c9abc1649 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Poskytovateľ OCR",
+ "ocrProviderTip": "Rozpoznávanie offline v lokálnom jadre; Tesseract nainštalujte samostatne; pri nedostupnosti sa poskytovateľ automaticky nemení",
+ "ocrAuto": "Automatické OCR",
+ "ocrAutoTip": "Spracovať obrázky bežných zápisníkov, ktoré ešte nemajú výsledok OCR",
+ "ocrModel": "Model OCR",
+ "ocrModelTip": "Tiny a Small sú vstavané; zmena zachová existujúce výsledky; OCR zopakujte z ponuky obrázka",
+ "ocrImportModels": "Importovať modely OCR",
+ "ocrImportModelsTip": "Vyberte kompatibilné súbory ONNX detekcie a rozpoznávania PP-OCRv6 a ich súbory inference.yml; importované súbory sa synchronizujú s pracovným priestorom",
+ "ocrDetector": "Detekčný model",
+ "ocrRecognizer": "Model rozpoznávania",
+ "ocrUnavailable": "Nedostupné",
"pinWindow": "Ponechať okno navrchu",
"unpinWindow": "Zrušiť ponechanie okna navrchu",
"settingsWindowMode": "Otvárať nastavenia v",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index dea9435d06..a67cee59ad 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR добављач",
+ "ocrProviderTip": "Препознавање ван мреже у локалном језгру; Tesseract инсталирајте засебно; нема аутоматске промене ако није доступан",
+ "ocrAuto": "Аутоматски OCR",
+ "ocrAutoTip": "Обрађуј слике обичних бележница које још немају OCR резултат",
+ "ocrModel": "OCR модел",
+ "ocrModelTip": "Tiny и Small су уграђени; промена чува постојеће резултате; поновите OCR из менија слике",
+ "ocrImportModels": "Увези OCR моделе",
+ "ocrImportModelsTip": "Изаберите компатибилне PP-OCRv6 ONNX датотеке за детекцију и препознавање и њихове inference.yml датотеке; увезене датотеке се синхронизују са радним простором",
+ "ocrDetector": "Модел детекције",
+ "ocrRecognizer": "Модел препознавања",
+ "ocrUnavailable": "Недоступно",
"pinWindow": "Држи прозор на врху",
"unpinWindow": "Престани да држиш прозор на врху",
"settingsWindowMode": "Место отварања подешавања",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index d9f891d079..391dd737bd 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "ผู้ให้บริการ OCR",
+ "ocrProviderTip": "รู้จำแบบออฟไลน์ในเคอร์เนลของเครื่อง ต้องติดตั้ง Tesseract แยกต่างหาก และจะไม่สลับโดยอัตโนมัติเมื่อใช้งานไม่ได้",
+ "ocrAuto": "OCR อัตโนมัติ",
+ "ocrAutoTip": "ประมวลผลรูปภาพในสมุดบันทึกทั่วไปที่ยังไม่มีผล OCR",
+ "ocrModel": "โมเดล OCR",
+ "ocrModelTip": "มี Tiny และ Small ในตัว การสลับจะเก็บผลเดิมไว้ และสั่ง OCR ใหม่ได้จากเมนูรูปภาพ",
+ "ocrImportModels": "นำเข้าโมเดล OCR",
+ "ocrImportModelsTip": "เลือกไฟล์ ONNX สำหรับตรวจจับและรู้จำ PP-OCRv6 ที่เข้ากันได้ พร้อม inference.yml ของแต่ละโมเดล ไฟล์ที่นำเข้าจะซิงค์กับพื้นที่ทำงาน",
+ "ocrDetector": "โมเดลตรวจจับ",
+ "ocrRecognizer": "โมเดลรู้จำ",
+ "ocrUnavailable": "ใช้งานไม่ได้",
"pinWindow": "ให้หน้าต่างอยู่ด้านบนเสมอ",
"unpinWindow": "ยกเลิกให้หน้าต่างอยู่ด้านบนเสมอ",
"settingsWindowMode": "ตำแหน่งเปิดการตั้งค่า",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index cd2a70d008..133f723fac 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR sağlayıcısı",
+ "ocrProviderTip": "Yerel çekirdekte çevrimdışı tanıma; Tesseract ayrı kurulmalıdır; kullanılamadığında otomatik geçiş yapılmaz",
+ "ocrAuto": "Otomatik OCR",
+ "ocrAutoTip": "Henüz OCR sonucu olmayan normal defter görüntülerini işle",
+ "ocrModel": "OCR modeli",
+ "ocrModelTip": "Tiny ve Small yerleşiktir; değiştirmek mevcut sonuçları korur; görüntü menüsünden OCR işlemini tekrarlayın",
+ "ocrImportModels": "OCR modellerini içe aktar",
+ "ocrImportModelsTip": "Uyumlu PP-OCRv6 algılama ve tanıma ONNX dosyalarını ve inference.yml dosyalarını seçin; içe aktarılan dosyalar çalışma alanıyla eşitlenir",
+ "ocrDetector": "Algılama modeli",
+ "ocrRecognizer": "Tanıma modeli",
+ "ocrUnavailable": "Kullanılamıyor",
"pinWindow": "Pencereyi her zaman üstte tut",
"unpinWindow": "Pencereyi her zaman üstte tutmayı bırak",
"settingsWindowMode": "Ayarların açılacağı yer",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index fb18b8f193..5c779d5704 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "Провайдер OCR",
+ "ocrProviderTip": "Розпізнавання офлайн у локальному ядрі; встановіть Tesseract окремо; автоматичного перемикання за недоступності немає",
+ "ocrAuto": "Автоматичний OCR",
+ "ocrAutoTip": "Обробляти зображення звичайних блокнотів, які ще не мають результату OCR",
+ "ocrModel": "Модель OCR",
+ "ocrModelTip": "Tiny і Small вбудовані; зміна зберігає наявні результати; повторіть OCR з меню зображення",
+ "ocrImportModels": "Імпорт моделей OCR",
+ "ocrImportModelsTip": "Виберіть сумісні ONNX-файли виявлення та розпізнавання PP-OCRv6 і відповідні inference.yml; імпортовані файли синхронізуються з робочим простором",
+ "ocrDetector": "Модель виявлення",
+ "ocrRecognizer": "Модель розпізнавання",
+ "ocrUnavailable": "Недоступний",
"pinWindow": "Показувати вікно поверх інших",
"unpinWindow": "Не показувати вікно поверх інших",
"settingsWindowMode": "Де відкривати налаштування",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index f256ce64c1..06065f68cb 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR 提供商",
+ "ocrProviderTip": "由本机内核离线识别;Tesseract 需自行安装;不可用时不会自动切换",
+ "ocrAuto": "自动 OCR",
+ "ocrAutoTip": "仅处理尚无 OCR 结果的普通笔记本图片",
+ "ocrModel": "OCR 模型",
+ "ocrModelTip": "Tiny 和 Small 已内置;切换后保留现有结果,可在图片菜单中重新识别",
+ "ocrImportModels": "导入 OCR 模型",
+ "ocrImportModelsTip": "选择配套的 PP-OCRv6 检测、识别 ONNX 文件及各自的 inference.yml;导入文件随工作空间同步",
+ "ocrDetector": "检测模型",
+ "ocrRecognizer": "识别模型",
+ "ocrUnavailable": "不可用",
"pinWindow": "置顶窗口",
"unpinWindow": "取消置顶窗口",
"settingsWindowMode": "打开设置位置",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index c2201a4d75..ed5004fbc4 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,15 @@
{
+ "ocrProvider": "OCR 提供者",
+ "ocrProviderTip": "由本機核心離線辨識;Tesseract 需自行安裝;無法使用時不會自動切換",
+ "ocrAuto": "自動 OCR",
+ "ocrAutoTip": "僅處理尚無 OCR 結果的一般筆記本圖片",
+ "ocrModel": "OCR 模型",
+ "ocrModelTip": "已內建 Tiny 和 Small;切換後保留現有結果,可在圖片選單中重新辨識",
+ "ocrImportModels": "匯入 OCR 模型",
+ "ocrImportModelsTip": "選取配套的 PP-OCRv6 偵測、辨識 ONNX 檔案及各自的 inference.yml;匯入檔案隨工作空間同步",
+ "ocrDetector": "偵測模型",
+ "ocrRecognizer": "辨識模型",
+ "ocrUnavailable": "無法使用",
"pinWindow": "置頂視窗",
"unpinWindow": "取消置頂視窗",
"settingsWindowMode": "開啟設定位置",
diff --git a/app/electron-builder-arm64.yml b/app/electron-builder-arm64.yml
index 0cf419e938..6100259ffb 100644
--- a/app/electron-builder-arm64.yml
+++ b/app/electron-builder-arm64.yml
@@ -13,6 +13,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "LICENSE"
@@ -51,6 +52,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/windows-arm64"
+ to: "stage/ocr/runtime/windows-arm64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/electron-builder-darwin-arm64.yml b/app/electron-builder-darwin-arm64.yml
index fc3c77b573..59b207bcdb 100644
--- a/app/electron-builder-darwin-arm64.yml
+++ b/app/electron-builder-darwin-arm64.yml
@@ -12,6 +12,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "Resources/LICENSE"
@@ -45,6 +46,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/darwin-arm64"
+ to: "stage/ocr/runtime/darwin-arm64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/electron-builder-darwin.yml b/app/electron-builder-darwin.yml
index 657a36b343..49fec92250 100644
--- a/app/electron-builder-darwin.yml
+++ b/app/electron-builder-darwin.yml
@@ -12,6 +12,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "Resources/LICENSE"
@@ -45,6 +46,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/darwin-amd64"
+ to: "stage/ocr/runtime/darwin-amd64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/electron-builder-linux-arm64.yml b/app/electron-builder-linux-arm64.yml
index 0c67562b32..9ce97a550a 100644
--- a/app/electron-builder-linux-arm64.yml
+++ b/app/electron-builder-linux-arm64.yml
@@ -12,6 +12,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "LICENSE"
@@ -54,6 +55,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/linux-arm64"
+ to: "stage/ocr/runtime/linux-arm64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/electron-builder-linux.yml b/app/electron-builder-linux.yml
index 3c3a6faae0..9fb331d17b 100644
--- a/app/electron-builder-linux.yml
+++ b/app/electron-builder-linux.yml
@@ -12,6 +12,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "LICENSE"
@@ -51,6 +52,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/linux-amd64"
+ to: "stage/ocr/runtime/linux-amd64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/electron-builder.yml b/app/electron-builder.yml
index 89d08d61e1..eed41b0ed4 100644
--- a/app/electron-builder.yml
+++ b/app/electron-builder.yml
@@ -13,6 +13,7 @@ directories:
files:
- "electron"
afterPack: "./scripts/afterPack.js"
+beforePack: "./scripts/beforePack.js"
extraFiles:
- from: "../LICENSE"
to: "LICENSE"
@@ -50,6 +51,9 @@ extraResources:
to: "changelogs"
- from: "stage"
to: "stage"
+ filter: ["**/*", "!ocr/runtime/**/*"]
+ - from: "stage/ocr/runtime/windows-amd64"
+ to: "stage/ocr/runtime/windows-amd64"
- from: "guide"
to: "guide"
filter: "!**/{.DS_Store,.git,.gitignore,.idea}"
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
index 11b17c7a36..3b6c22a9f4 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
@@ -6,7 +6,7 @@
"id": "20200924100744-br924ar",
"title": "Assets",
"type": "doc",
- "updated": "20260930093600"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -967,7 +967,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003636-epvk98g",
- "updated": "20230117003636"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -981,21 +981,67 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117003636-0buf00n",
- "updated": "20230820185510"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "This feature is only supported on the desktop, and the "
+ "Data": "In "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
},
{
"Type": "NodeTextMark",
- "TextMarkType": "em",
- "TextMarkTextContent": "Tesseract OCR"
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Assets"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
},
{
"Type": "NodeText",
- "Data": " program needs to be manually installed first. "
+ "Data": " select Tesseract or PaddleOCR and enable automatic OCR. Recognition runs offline in the kernel without an open interface. Tesseract requires a separate desktop installation."
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-e9wid3h",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-e9wid3h",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "PaddleOCR includes PP-OCRv6 Tiny and Small models, available offline without downloading. Tiny uses fewer resources; Small offers higher accuracy. To import another compatible PP-OCRv6 model, select its detection and recognition ONNX files and the corresponding inference.yml files. Imported models sync with the workspace; the provider and selected model are saved per device."
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-ogz08vw",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-ogz08vw",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "The selected provider handles both automatic and manual recognition. Switching preserves existing results; use the image menu to rerun OCR explicitly. Failures preserve the previous result and do not switch providers. Text remains available for image text search and editing. Encrypted notebooks do not participate in OCR."
}
]
},
@@ -1028,7 +1074,7 @@
"ListData": {},
"Properties": {
"id": "20230202231731-bdh7lab",
- "updated": "20231110112758"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1040,7 +1086,7 @@
},
"Properties": {
"id": "20230202231732-n7z8jth",
- "updated": "20231110112758"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1048,7 +1094,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231732-f3jkj7p",
- "updated": "20231110112758"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1080,12 +1126,12 @@
},
{
"Type": "NodeText",
- "Data": "​ in the kernel boot log; If you want to disable OCR, set the environment variable "
+ "Data": "​ in the kernel boot log; If you want to disable Tesseract, set the environment variable "
},
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "SIYUAN\\_TESSERACT\\_ENABLED=false"
+ "TextMarkTextContent": "SIYUAN_TESSERACT_ENABLED=false"
},
{
"Type": "NodeText",
@@ -1104,7 +1150,7 @@
},
"Properties": {
"id": "20230202231800-z8hswmk",
- "updated": "20230211103154"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1112,7 +1158,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231800-c3x45ky",
- "updated": "20230211103154"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1121,7 +1167,7 @@
},
{
"Type": "NodeText",
- "Data": " does not enable all installed language packs, because too many language packs will cause OCR to be slow or even timeout and return empty results, and take up too many system resources, so by default only "
+ "Data": " does not enable all installed language packs, because too many language packs will cause OCR to be slow or time out, and take up too many system resources, so by default only "
},
{
"Type": "NodeTextMark",
@@ -1216,7 +1262,8 @@
"Marker": "Kg=="
},
"Properties": {
- "id": "20230211102830-9azqf9m"
+ "id": "20230211102830-9azqf9m",
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1224,12 +1271,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102830-sbchex4",
- "updated": "20230211102832"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Only images in png and jpg formats are supported"
+ "Data": "Both providers support PNG, JPEG, TIFF, BMP, GIF, and WebP images; Tesseract also supports PBM, PGM, PPM, and PNM"
}
]
}
@@ -1244,7 +1291,7 @@
},
"Properties": {
"id": "20230211102834-fx3o5su",
- "updated": "20230211102928"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1252,12 +1299,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102834-3jzjdrv",
- "updated": "20230211102928"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "By default, only images below 2MB are processed. If you need to adjust, you can set the environment variable "
+ "Data": "For Tesseract, By default, only images below 2MB are processed. If you need to adjust, you can set the environment variable "
},
{
"Type": "NodeTextMark",
@@ -1275,7 +1322,7 @@
},
{
"Type": "NodeText",
- "Data": "​​ adjust the upper limit to 4MB"
+ "Data": "​​ adjust the upper limit to 4MB; PaddleOCR supports images up to 32 MiB and 24 million pixels"
}
]
}
@@ -1288,12 +1335,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117003636-ouxlaen",
- "updated": "20230117003636"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "Image OCR extracts text automatically in the background, currently only supports PNG and JPG images. The extracted text is used in the search function, so that images can be located by text keywords."
+ "Data": "When automatic OCR is enabled, the kernel processes images that have no existing OCR result. Extracted text is used by search to locate images by their text."
}
]
},
@@ -1303,7 +1350,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202934-1h96or8",
- "updated": "20230414202934"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1416,12 +1463,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230414203027-chylp3d",
- "updated": "20260720201253"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "After the adjustment, you need to manually rebuild the asset content index."
+ "Data": "Changes saved in the image result editor automatically update search indexes. After editing the JSON file outside SiYuan, rebuild the asset content index"
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
index daa407033b..9154a44514 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
@@ -6,7 +6,7 @@
"id": "20200915214115-42b8zma",
"title": "资源文件",
"type": "doc",
- "updated": "20260930093600"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -979,7 +979,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117002036-vmc0mx4",
- "updated": "20230117002509"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -993,21 +993,67 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117002059-ssmlejt",
- "updated": "20230820185522"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "该特性仅在桌面端支持,并且需要先手动安装 "
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "设置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
},
{
"Type": "NodeTextMark",
- "TextMarkType": "em",
- "TextMarkTextContent": "Tesseract OCR"
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "资源"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
},
{
"Type": "NodeText",
- "Data": " 程序。"
+ "Data": " 中选择 Tesseract 或 PaddleOCR,并设置是否自动识别。识别由内核离线执行,无需打开界面。使用 Tesseract 时,需在桌面端自行安装该程序。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-4enj18s",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-4enj18s",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "PaddleOCR 内置 PP-OCRv6 Tiny 和 Small 模型,无需下载即可离线使用。Tiny 占用资源更少,Small 识别精度更高。导入其他兼容的 PP-OCRv6 模型时,分别选择检测、识别 ONNX 文件及对应的 inference.yml。导入模型随工作空间同步,提供商和当前模型的选择按设备保存。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-6l7ji97",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-6l7ji97",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "手动识别和自动识别均使用所选提供商。切换后保留已有结果,可通过图片菜单主动重新识别。识别失败时保留上次结果,也不会自动切换提供商。文本继续用于图片文字搜索和结果编辑。加密笔记本不参与 OCR。"
}
]
},
@@ -1040,7 +1086,7 @@
"ListData": {},
"Properties": {
"id": "20230202231309-pcjl7c2",
- "updated": "20231110112936"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1052,7 +1098,7 @@
},
"Properties": {
"id": "20230202231311-7qdk1za",
- "updated": "20231110112936"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1060,7 +1106,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231311-n1pf7in",
- "updated": "20231110112936"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1092,7 +1138,7 @@
},
{
"Type": "NodeText",
- "Data": "​;如果要禁用 OCR,请设置环境变量 "
+ "Data": "​;如果要禁用 Tesseract,请设置环境变量 "
},
{
"Type": "NodeTextMark",
@@ -1116,7 +1162,7 @@
},
"Properties": {
"id": "20230202231321-q1b1tza",
- "updated": "20230211103207"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1124,12 +1170,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231321-5ugmgf0",
- "updated": "20230211103207"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "思源并不会启用所有已安装的语言包,因为语言包太多的话会导致 OCR 缓慢甚至超时返回空结果,并且占用过多的系统资源,所以默认最多只会启用 "
+ "Data": "思源并不会启用所有已安装的语言包,因为语言包太多的话会导致 OCR 缓慢甚至超时,并且占用过多的系统资源,所以默认最多只会启用 "
},
{
"Type": "NodeTextMark",
@@ -1225,7 +1271,7 @@
},
"Properties": {
"id": "20230211102440-0qik4dd",
- "updated": "20230211102642"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1233,12 +1279,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102440-09cmf75",
- "updated": "20230211102642"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "仅支持 png 和 jpg 格式的图片"
+ "Data": "两种提供商均支持 PNG、JPEG、TIFF、BMP、GIF 和 WebP 图片,Tesseract 还支持 PBM、PGM、PPM 和 PNM"
}
]
}
@@ -1253,7 +1299,7 @@
},
"Properties": {
"id": "20230211102601-ifl3ojm",
- "updated": "20230211102744"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1261,12 +1307,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102601-npe6hvh",
- "updated": "20230211102744"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "默认只对 2MB 以下的图片进行处理,如果需要调整,可以通过环境变量 "
+ "Data": "Tesseract 默认只对 2MB 以下的图片进行处理,如果需要调整,可以通过环境变量 "
},
{
"Type": "NodeTextMark",
@@ -1284,7 +1330,7 @@
},
{
"Type": "NodeText",
- "Data": "​ 将上限调整为 4MB"
+ "Data": "​ 将上限调整为 4MB;PaddleOCR 支持不超过 32 MiB、2400 万像素的图片"
}
]
}
@@ -1297,12 +1343,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117002511-ex9qrjy",
- "updated": "20230117003207"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "图片 OCR 提取文本过程是自动在后台进行的,目前仅支持 PNG、JPG 图片。提取的文本会被用于搜索功能,这样就能通过文本关键字来定位图片。"
+ "Data": "启用自动 OCR 后,内核会处理尚无 OCR 结果的图片,提取的文本用于搜索,可通过文字关键词定位图片。"
}
]
},
@@ -1312,7 +1358,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202710-a51lo76",
- "updated": "20230414202726"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1425,12 +1471,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230414202749-qbcnypq",
- "updated": "20260720201253"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "调整完以后需要手动重建资源文件索引。"
+ "Data": "通过图片结果编辑窗口保存后会自动更新搜索索引;在思源外部修改 JSON 文件后,需手动重建资源文件索引"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
index 8aa430e89a..8d58ccb34e 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
@@ -6,7 +6,7 @@
"id": "20211226123038-4umgpxy",
"title": "資料文件",
"type": "doc",
- "updated": "20260930093600"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -965,7 +965,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003901-ze4mbzz",
- "updated": "20230117003901"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -979,21 +979,67 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117003901-5pfzttc",
- "updated": "20230820185516"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "該特性僅在桌面端支持,並且需要先手動安裝 "
+ "Data": "在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
},
{
"Type": "NodeTextMark",
- "TextMarkType": "em",
- "TextMarkTextContent": "Tesseract OCR"
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "資源"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
},
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 中選擇 Tesseract 或 PaddleOCR,並設定是否自動辨識。辨識由核心離線執行,無需開啟介面。使用 Tesseract 時,需在桌面端自行安裝該程式。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-w0zyvyj",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-w0zyvyj",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "PaddleOCR 內建 PP-OCRv6 Tiny 和 Small 模型,無需下載即可離線使用。Tiny 占用資源較少,Small 辨識精確度較高。匯入其他相容的 PP-OCRv6 模型時,分別選取偵測、辨識 ONNX 檔案及對應的 inference.yml。匯入模型隨工作空間同步,提供者和目前模型的選擇依裝置儲存。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-hc489un",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-hc489un",
+ "updated": "20261001000112"
+ },
+ "Children": [
{
"Type": "NodeText",
- "Data": " 程序。"
+ "Data": "手動辨識和自動辨識均使用所選提供者。切換後保留已有結果,可透過圖片選單主動重新辨識。辨識失敗時保留上次結果,也不會自動切換提供者。文字繼續用於圖片文字搜尋和結果編輯。加密筆記本不參與 OCR。"
}
]
},
@@ -1026,7 +1072,7 @@
"ListData": {},
"Properties": {
"id": "20230202231516-o6k9mj1",
- "updated": "20231110112927"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1038,7 +1084,7 @@
},
"Properties": {
"id": "20230202231516-pwj2ndg",
- "updated": "20231110112927"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1046,7 +1092,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231516-8trf08t",
- "updated": "20231110112927"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1078,7 +1124,7 @@
},
{
"Type": "NodeText",
- "Data": "​;如果要停用 OCR,請設定環境變量 "
+ "Data": "​;如果要停用 Tesseract,請設定環境變量 "
},
{
"Type": "NodeTextMark",
@@ -1102,7 +1148,7 @@
},
"Properties": {
"id": "20230202231519-x47s7he",
- "updated": "20230211103203"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1110,12 +1156,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230202231519-04f6dh6",
- "updated": "20230211103203"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "思源並不會啟用所有已安裝的語言包,因為語言包太多的話會導致 OCR 緩慢甚至超時返回空結果,並且佔用過多的系統資源,所以預設最多只會啟用 "
+ "Data": "思源並不會啟用所有已安裝的語言包,因為語言包太多的話會導致 OCR 緩慢甚至逾時,並且佔用過多的系統資源,所以預設最多只會啟用 "
},
{
"Type": "NodeTextMark",
@@ -1210,7 +1256,8 @@
"Marker": "Kg=="
},
"Properties": {
- "id": "20230211102853-w8ykvqx"
+ "id": "20230211102853-w8ykvqx",
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1218,12 +1265,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102853-4lc4az0",
- "updated": "20230211102856"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "僅支持 png 和 jpg 格式的圖片"
+ "Data": "兩種提供者均支援 PNG、JPEG、TIFF、BMP、GIF 和 WebP 圖片,Tesseract 還支援 PBM、PGM、PPM 和 PNM"
}
]
}
@@ -1238,7 +1285,7 @@
},
"Properties": {
"id": "20230211102858-0lgz6pc",
- "updated": "20230211102910"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1246,12 +1293,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230211102858-mfhvy7x",
- "updated": "20230211102910"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "預設只對 2MB 以下的圖片進行處理,如果需要調整,可以通過環境變量 "
+ "Data": "Tesseract 預設只對 2MB 以下的圖片進行處理,如果需要調整,可以通過環境變量 "
},
{
"Type": "NodeTextMark",
@@ -1269,7 +1316,7 @@
},
{
"Type": "NodeText",
- "Data": "​ 將上限調整為 4MB"
+ "Data": "​ 將上限調整為 4MB;PaddleOCR 支援不超過 32 MiB、2400 萬像素的圖片"
}
]
}
@@ -1282,12 +1329,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230117003901-j7r2o7f",
- "updated": "20230117003901"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "圖片 OCR 提取文字過程是自動在後台進行的,目前僅支持 PNG、JPG 圖片。提取的文字會被用於搜索功能,這樣就能通過文字關鍵字來定位圖片。"
+ "Data": "啟用自動 OCR 後,核心會處理尚無 OCR 結果的圖片,提取的文字用於搜尋,可透過文字關鍵字定位圖片。"
}
]
},
@@ -1297,7 +1344,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414203058-foirrwk",
- "updated": "20230414203058"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1410,12 +1457,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20230414203058-pvk5pnz",
- "updated": "20260720201253"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "調整完以後需要手動重建資源檔案索引。"
+ "Data": "透過圖片結果編輯視窗儲存後會自動更新搜尋索引;在思源外部修改 JSON 檔案後,需手動重建資源檔案索引"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
index e06225a2d9..9d8e77a65d 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-1m5un7l",
"title": "アセット",
"type": "doc",
- "updated": "20260930093600"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1005,7 +1005,7 @@
"Properties": {
"ID": "20240530101000-5bix8t1",
"id": "20240530101000-9evyuhr",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1020,22 +1020,63 @@
"Properties": {
"ID": "20240530101000-fl1bsnw",
"id": "20240530101000-t4ud4y2",
- "updated": "20240530101000"
+ "updated": "20261001000112"
},
"Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
{
"Type": "NodeText",
- "Data": "この機能はデスクトップ版のみサポートされており、事前に "
+ "Data": " - "
},
{
"Type": "NodeTextMark",
- "TextMarkType": "a",
- "TextMarkAHref": "https://github.com/tesseract-ocr/tesseract",
- "TextMarkTextContent": "Tesseract OCR"
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "アセット"
},
{
"Type": "NodeText",
- "Data": " プログラムをインストールしておく必要があります。"
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で Tesseract または PaddleOCR を選択し、自動認識を設定します。認識はカーネルでオフライン実行され、画面を開く必要はありません。Tesseract はデスクトップに別途インストールしてください。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-ooz689o",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-ooz689o",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "PaddleOCR には PP-OCRv6 Tiny と Small が内蔵され、ダウンロードせずにオフラインで使用できます。Tiny はリソース消費が少なく、Small は認識精度が高いモデルです。ほかの互換 PP-OCRv6 モデルをインポートする場合は、検出と認識の ONNX ファイルと各 inference.yml を選択します。インポートしたモデルはワークスペースと同期され、プロバイダーと使用モデルの選択は端末ごとに保存されます。"
+ }
+ ]
+ },
+ {
+ "ID": "20261001000112-87qzkfr",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261001000112-87qzkfr",
+ "updated": "20261001000112"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "手動認識と自動認識は選択したプロバイダーを使用します。切り替えても既存の結果は保持され、画像メニューから明示的に再認識できます。失敗した場合は前回の結果を保持し、プロバイダーを自動切り替えしません。テキストは画像の文字検索と結果の編集に引き続き使用されます。暗号化ノートブックは OCR の対象外です。"
}
]
},
@@ -1070,7 +1111,7 @@
"Properties": {
"ID": "20240530101000-mbaa8ar",
"id": "20240530101000-qmvr8rd",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1083,7 +1124,7 @@
"Properties": {
"ID": "20240530101000-lw8ri1k",
"id": "20240530101000-vuyib46",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1092,7 +1133,7 @@
"Properties": {
"ID": "20240530101000-9ucri2d",
"id": "20240530101000-ciyew7k",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1124,12 +1165,12 @@
},
{
"Type": "NodeText",
- "Data": "​ と表示されます。OCR を無効にしたい場合は、環境変数に "
+ "Data": "​ と表示されます。Tesseract を無効にしたい場合は、環境変数に "
},
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "SIYUAN\\_TESSERACT\\_ENABLED=false"
+ "TextMarkTextContent": "SIYUAN_TESSERACT_ENABLED=false"
},
{
"Type": "NodeText",
@@ -1149,7 +1190,7 @@
"Properties": {
"ID": "20240530101000-xjhk4ih",
"id": "20240530101000-yp8d881",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1158,12 +1199,12 @@
"Properties": {
"ID": "20240530101000-04xwhm0",
"id": "20240530101000-juctxsf",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "SiYuan はインストールされたすべての言語パックを有効にするわけではありません。言語パックが多すぎると、OCR が遅くなったり、タイムアウトして空の結果が返されたり、システムリソースを過剰に消費する可能性があるためです。そのため、デフォルトでは、最大で "
+ "Data": "SiYuan はインストールされたすべての言語パックを有効にするわけではありません。言語パックが多すぎると、OCR が遅くなったり、タイムアウトしたり、システムリソースを過剰に消費する可能性があるためです。そのため、デフォルトでは、最大で "
},
{
"Type": "NodeTextMark",
@@ -1260,7 +1301,7 @@
"Properties": {
"ID": "20240530101000-prezj3g",
"id": "20240530101000-8vlvsns",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1269,12 +1310,12 @@
"Properties": {
"ID": "20240530101000-9as1nfh",
"id": "20240530101000-ack0scp",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "png と jpg 形式の画像のみがサポートされています。"
+ "Data": "両方のプロバイダーは PNG、JPEG、TIFF、BMP、GIF、WebP 画像をサポートし、Tesseract は PBM、PGM、PPM、PNM もサポートします"
}
]
}
@@ -1290,7 +1331,7 @@
"Properties": {
"ID": "20240530101000-w91nsfc",
"id": "20240530101000-5mse6p6",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1299,12 +1340,12 @@
"Properties": {
"ID": "20240530101000-oiv9z77",
"id": "20240530101000-vsrr7lg",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "デフォルトでは 2MB 以下の画像のみが処理されます。変更する場合は環境変数 "
+ "Data": "Tesseract は、デフォルトでは 2MB 以下の画像のみが処理されます。変更する場合は環境変数 "
},
{
"Type": "NodeTextMark",
@@ -1322,7 +1363,7 @@
},
{
"Type": "NodeText",
- "Data": "​ は上限を 4MB に変更します)。"
+ "Data": "​ は上限を 4MB に変更します)。PaddleOCR は 32 MiB 以下、2400 万画素以下の画像をサポートします"
}
]
}
@@ -1336,12 +1377,12 @@
"Properties": {
"ID": "20240530101000-bhe8w6i",
"id": "20240530101000-hvmv9gg",
- "updated": "20240530101000"
+ "updated": "20261001000112"
},
"Children": [
{
"Type": "NodeText",
- "Data": "画像の OCR はバックグラウンドで自動的に行われます。現在、PNG と JPG 画像のみをサポートしています。抽出されたテキストは検索機能で使用され、テキストキーワードによって画像を見つけることができます。"
+ "Data": "自動 OCR を有効にすると、カーネルは OCR 結果のない画像を処理します。抽出したテキストは検索に使用され、文字のキーワードで画像を見つけられます。"
}
]
},
@@ -1352,7 +1393,7 @@
"Properties": {
"ID": "20240530101000-aefldsk",
"id": "20240530101000-cpod2qy",
- "updated": "20240530101000"
+ "updated": "20261001013550"
},
"Children": [
{
@@ -1472,12 +1513,12 @@
"Properties": {
"ID": "20240530101000-ys1z20f",
"id": "20240530101000-rq0etyj",
- "updated": "20260720201253"
+ "updated": "20261001013550"
},
"Children": [
{
"Type": "NodeText",
- "Data": "調整後は手動でアセットコンテンツインデックスを再構築する必要があります。"
+ "Data": "画像の結果編集画面で保存すると検索インデックスが自動更新されます。SiYuan の外部で JSON ファイルを編集した場合は、アセットコンテンツインデックスを手動で再構築してください"
}
]
},
diff --git a/app/scripts/beforePack.js b/app/scripts/beforePack.js
new file mode 100644
index 0000000000..93a5ff0886
--- /dev/null
+++ b/app/scripts/beforePack.js
@@ -0,0 +1,27 @@
+const {spawn} = require("child_process");
+const path = require("path");
+const {Arch} = require("electron-builder");
+
+function prepareArguments(context) {
+ const platform = context.electronPlatformName === "win32" ? "windows" : context.electronPlatformName;
+ if (!["windows", "darwin", "linux"].includes(platform) || ![Arch.arm64, Arch.x64].includes(context.arch)) {
+ throw new Error("Unsupported OCR packaging target");
+ }
+ const arch = context.arch === Arch.arm64 ? "arm64" : "amd64";
+ const args = [path.resolve(__dirname, "../../scripts/prepare-ocr.py"), "--runtime", `${platform}-${arch}`];
+ if (platform === "linux") {
+ args.push("--build-worker");
+ }
+ return args;
+}
+
+module.exports = async function beforePack(context) {
+ const args = prepareArguments(context);
+ await new Promise((resolve, reject) => {
+ const child = spawn(process.platform === "win32" ? "python" : "python3", args, {stdio: "inherit"});
+ child.on("error", reject);
+ child.on("exit", code => code === 0 ? resolve() : reject(new Error(`OCR resource preparation failed: ${code}`)));
+ });
+};
+
+module.exports.prepareArguments = prepareArguments;
diff --git a/app/scripts/beforePack.test.js b/app/scripts/beforePack.test.js
new file mode 100644
index 0000000000..e6c3122b47
--- /dev/null
+++ b/app/scripts/beforePack.test.js
@@ -0,0 +1,20 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const {Arch} = require("electron-builder");
+const {prepareArguments} = require("./beforePack");
+
+test("OCR packaging selects each desktop runtime and the Linux headless worker", () => {
+ for (const platform of ["win32", "darwin", "linux"]) {
+ for (const arch of [Arch.x64, Arch.arm64]) {
+ const args = prepareArguments({electronPlatformName: platform, arch});
+ assert.equal(args[1], "--runtime");
+ assert.equal(args[2], `${platform === "win32" ? "windows" : platform}-${arch === Arch.arm64 ? "arm64" : "amd64"}`);
+ assert.equal(args.includes("--build-worker"), platform === "linux");
+ }
+ }
+});
+
+test("unsupported OCR packaging targets fail before resources are prepared", () => {
+ assert.throws(() => prepareArguments({electronPlatformName: "win32", arch: Arch.ia32}), /Unsupported/);
+ assert.throws(() => prepareArguments({electronPlatformName: "freebsd", arch: Arch.x64}), /Unsupported/);
+});
diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scss
index b7d2a88cfb..61df11105d 100644
--- a/app/src/assets/scss/business/_config.scss
+++ b/app/src/assets/scss/business/_config.scss
@@ -1764,3 +1764,7 @@
pointer-events: auto;
}
}
+.config-ocr {
+ height: 100%;
+ overflow: auto;
+}
diff --git a/app/src/config/assets.ts b/app/src/config/assets.ts
index bf920bed55..5e8d9db99e 100644
--- a/app/src/config/assets.ts
+++ b/app/src/config/assets.ts
@@ -19,6 +19,7 @@ import {disabledProtyle, onGet} from "../protyle/util/onGet";
import {removeLoading} from "../protyle/ui/initUI";
import {switchSettingPanelSubTab} from "./setting/mount";
import {getHostCapabilities} from "../util/hostCapabilities";
+import {mountOCRSettings, ocrSearchStrings} from "./ocr";
/// #if MOBILE
import {openMobileFileById} from "../mobile/editor";
/// #else
@@ -31,6 +32,7 @@ export const collectAssetsTabSearchStrings = (): string[] => [
window.siyuan.languages.unreferencedAssets,
window.siyuan.languages.unreferencedAV,
window.siyuan.languages.missingAssets,
+ ...ocrSearchStrings(),
];
/** 资源 Tab 挂载(面板页,不走注册表渲染) */
@@ -52,6 +54,7 @@ export const mountAssetsTab = (root: HTMLElement, keywords?: string, app?: App)
{type: "remove", label: window.siyuan.languages.unreferencedAssets},
{type: "removeAV", label: window.siyuan.languages.unreferencedAV},
{type: "missing", label: window.siyuan.languages.missingAssets},
+ {type: "ocr", label: ocrSearchStrings().join(" ")},
]);
}
};
@@ -62,6 +65,8 @@ export const unmountAssetsTab = (root: Element) => {
return;
}
assets.editor?.destroy();
+ assets.unmountOCR?.();
+ assets.unmountOCR = undefined;
assets.editor = undefined;
assets.element = undefined;
};
@@ -69,6 +74,7 @@ export const unmountAssetsTab = (root: Element) => {
const assets = {
element: undefined as Element | undefined,
editor: undefined as Protyle | undefined,
+ unmountOCR: undefined as (() => void) | undefined,
genHTML: () => {
const mobile = isMobile();
return `<div class="fn__flex-column" style="height: 100%">
@@ -88,6 +94,9 @@ const assets = {
<span class="item__text">${window.siyuan.languages.missingAssets}</span>
<span class="fn__flex-1"></span>
</div>
+ <div class="item item--full" data-type="ocr">
+ <span class="fn__flex-1"></span><span class="item__text">OCR</span><span class="fn__flex-1"></span>
+ </div>
</div>
<div class="fn__flex-1">
<div class="config-assets${mobile ? " b3-list--mobile" : ""}" data-type="remove" data-init="true">
@@ -127,6 +136,7 @@ const assets = {
</ul>
<div class="fn__hr"></div>
</div>
+ <div class="fn__none config-assets config-ocr" data-type="ocr" data-init="true"></div>
</div>
</div>`;
},
@@ -135,6 +145,7 @@ const assets = {
if (!root) {
return;
}
+ assets.unmountOCR = mountOCRSettings(root.querySelector<HTMLElement>('.config-assets[data-type="ocr"]'));
const assetsListElement = root.querySelector('.config-assets[data-type="remove"] .config-assets__list');
const avListElement = root.querySelector('.config-assets[data-type="removeAV"] .config-assets__list');
const mobile = isMobile();
diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.ts
new file mode 100644
index 0000000000..330d2d53f3
--- /dev/null
+++ b/app/src/config/ocr.ts
@@ -0,0 +1,156 @@
+import type {OCRConfigData, SettingOCR} from "../types/api";
+import {fetchSyncPost} from "../util/fetch";
+import {ContractFormData} from "../util/contractFormData";
+import {escapeAttr, escapeHtml} from "../util/escape";
+import {genConfigItemMainHtml, genSwitchRow} from "./render/fragments";
+import {genButtonRowHtml} from "./render/render";
+import {showMessage} from "../dialog/message";
+
+export const ocrSearchStrings = (): string[] => [
+ "OCR", "Tesseract", "PaddleOCR", "Tiny", "Small",
+ window.siyuan.languages.ocrProvider,
+ window.siyuan.languages.ocrModel,
+ window.siyuan.languages.ocrAuto,
+ window.siyuan.languages.ocrImportModels,
+];
+
+export const mountOCRSettings = (root: HTMLElement): (() => void) => {
+ const controller = new AbortController();
+ let closed = false;
+ let data: OCRConfigData;
+ let busy = false;
+ const languages = window.siyuan.languages;
+ const selectRow = (id: string, title: string, desc: string, options: string) =>
+ `<label class="fn__flex b3-label config-item">${genConfigItemMainHtml(title, desc)}
+<span class="fn__space"></span><select id="${id}" class="b3-select fn__flex-center fn__size200">${options}</select></label>`;
+ const files = [
+ {id: "detector", title: languages.ocrDetector, suffix: "onnx"},
+ {id: "detectorConfig", title: `${languages.ocrDetector} - YAML`, suffix: "yml,yaml"},
+ {id: "recognizer", title: languages.ocrRecognizer, suffix: "onnx"},
+ {id: "recognizerConfig", title: `${languages.ocrRecognizer} - YAML`, suffix: "yml,yaml"},
+ ];
+ const updateControls = () => {
+ root.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLButtonElement>("input, select, button").forEach(element => {
+ element.disabled = busy;
+ });
+ root.querySelector<HTMLSelectElement>("#ocrModel").disabled = busy || data.config.provider !== "paddleocr";
+ root.querySelector<HTMLButtonElement>("#ocrImport").disabled = busy || files.some(file => !root.querySelector<HTMLInputElement>(`#${file.id}`).files?.length);
+ };
+ const render = () => {
+ root.innerHTML = selectRow("ocrProvider", languages.ocrProvider, languages.ocrProviderTip,
+ data.providers.map(provider => `<option value="${escapeAttr(provider.id)}" ${data.config.provider === provider.id ? "selected" : ""}>${provider.id === "paddleocr" ? "PaddleOCR" : "Tesseract"}${provider.available ? "" : ` (${escapeHtml(languages.ocrUnavailable)})`}</option>`).join("")) +
+ selectRow("ocrModel", languages.ocrModel, languages.ocrModelTip,
+ data.models.map(model => `<option value="${escapeAttr(model.id)}" ${model.id === data.config.model ? "selected" : ""}>${escapeHtml(model.name)}${model.builtIn ? ` (${escapeHtml(languages.builtIn)})` : ""}</option>`).join("")) +
+ genSwitchRow("ocrAuto", languages.ocrAuto, languages.ocrAutoTip, data.config.auto) +
+ `<div class="b3-label b3-label--inner">${genConfigItemMainHtml(languages.ocrImportModels, languages.ocrImportModelsTip)}
+${files.map(file => `<label class="fn__block"><span class="b3-label__text">${file.title}</span><input id="${file.id}" class="b3-text-field fn__block" type="file" accept="${file.suffix.split(",").map(suffix => `.${suffix}`).join(",")}"></label>`).join("")}</div>` +
+ genButtonRowHtml("ocrImport", "", undefined, languages.import, "iconDownload") +
+ genButtonRowHtml("ocrRefresh", "", undefined, languages.refresh, "iconRefresh");
+ updateControls();
+ };
+ const load = async () => {
+ const response = await fetchSyncPost("/api/asset/getOCRConfig", {}, undefined, true, controller.signal);
+ if (closed || response.code !== 0) {
+ if (!closed && !data) {
+ root.innerHTML = `<div class="b3-label">${escapeHtml(response.msg)}</div>`;
+ }
+ return;
+ }
+ data = response.data;
+ render();
+ };
+ const handleError = (error: Error) => {
+ if (!closed && error.name !== "AbortError") {
+ showMessage(error.message);
+ }
+ };
+ root.innerHTML = "<div class=\"fn__loading\"><img src=\"/stage/loading-pure.svg\"></div>";
+ root.addEventListener("change", async event => {
+ event.stopPropagation();
+ const target = event.target as HTMLInputElement | HTMLSelectElement;
+ if (busy || !data) {
+ return;
+ }
+ if (files.some(file => file.id === target.id)) {
+ updateControls();
+ return;
+ }
+ const config: SettingOCR = {
+ provider: root.querySelector<HTMLSelectElement>("#ocrProvider").value,
+ model: root.querySelector<HTMLSelectElement>("#ocrModel").value,
+ auto: root.querySelector<HTMLInputElement>("#ocrAuto").checked,
+ };
+ busy = true;
+ updateControls();
+ try {
+ const response = await fetchSyncPost("/api/asset/setOCRConfig", config, undefined, true, controller.signal);
+ if (response.code === 0) {
+ data.config = response.data;
+ window.siyuan.config.ocr = response.data;
+ }
+ } catch (error) {
+ handleError(error);
+ } finally {
+ busy = false;
+ if (!closed) {
+ root.querySelector<HTMLSelectElement>("#ocrProvider").value = data.config.provider;
+ root.querySelector<HTMLSelectElement>("#ocrModel").value = data.config.model;
+ root.querySelector<HTMLInputElement>("#ocrAuto").checked = data.config.auto;
+ updateControls();
+ }
+ }
+ }, {signal: controller.signal});
+ root.addEventListener("click", async event => {
+ event.stopPropagation();
+ const button = (event.target as HTMLElement).closest("button");
+ if (!button || busy || !data) {
+ return;
+ }
+ if (button.id === "ocrRefresh") {
+ busy = true;
+ updateControls();
+ try {
+ await load();
+ } catch (error) {
+ handleError(error);
+ } finally {
+ busy = false;
+ if (!closed) {
+ updateControls();
+ }
+ }
+ } else if (button.id === "ocrImport") {
+ busy = true;
+ updateControls();
+ try {
+ const response = await fetchSyncPost("/api/asset/importOCRModels", new ContractFormData({
+ detector: root.querySelector<HTMLInputElement>("#detector").files[0],
+ detectorConfig: root.querySelector<HTMLInputElement>("#detectorConfig").files[0],
+ recognizer: root.querySelector<HTMLInputElement>("#recognizer").files[0],
+ recognizerConfig: root.querySelector<HTMLInputElement>("#recognizerConfig").files[0],
+ }), undefined, true, controller.signal);
+ if (response.code === 0 && !closed) {
+ showMessage(languages.imported);
+ await load();
+ }
+ } catch (error) {
+ handleError(error);
+ } finally {
+ busy = false;
+ if (!closed) {
+ updateControls();
+ }
+ }
+ }
+ }, {signal: controller.signal});
+ void load().catch(error => {
+ handleError(error);
+ if (!closed) {
+ root.innerHTML = `<div class="b3-label">${escapeHtml(error.message)}</div>`;
+ }
+ });
+ return () => {
+ closed = true;
+ controller.abort();
+ };
+};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index dbce06aced..85879e1db7 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1234,6 +1234,8 @@ export type ImportNotebookArchiveRequestInput = { "file": Blob; "key"?: Blob; "p
export type ImportNotebookCryptoBackupRequestInput = { "file": Blob; "password"?: string; };
+export type ImportOCRModelsRequestInput = { "detector": Blob; "detectorConfig": Blob; "recognizer": Blob; "recognizerConfig": Blob; };
+
export type ImportRepoKeyRequestInput = { "key": string; };
export type ImportSYRequestInput = { "file"?: Blob; "notebook"?: string; "toPath"?: string; };
@@ -1450,6 +1452,12 @@ export type NotificationData = { "id": string; };
export type NotificationRequestInput = { "msg": string; "timeout"?: number | null; };
+export type OCRConfigData = { "config": SettingOCR; "models": Array<OCRModel> | null; "providers": Array<OCRProviderState> | null; };
+
+export type OCRModel = { "builtIn": boolean; "id": string; "name": string; };
+
+export type OCRProviderState = { "available": boolean; "id": string; };
+
export type ObsidianAnalysisRequestInput = { "localPath": string; };
export type ObsidianImportRequestInput = { "notebookName": string; "taskID": string; };
@@ -1970,6 +1978,10 @@ export type SettingNotifications = { "browserCompatibility": boolean; "docTreeMa
export type SettingNotificationsInput = { "browserCompatibility"?: boolean | null; "docTreeMaxList"?: boolean | null; "formatPainterTip"?: boolean | null; "selectAllIncompleteTip"?: boolean | null; "selectAllTip"?: boolean | null; "tagMaxList"?: boolean | null; "workspaceNotSSD"?: boolean | null; };
+export type SettingOCR = { "auto": boolean; "model": string; "provider": string; };
+
+export type SettingOCRInput = { "auto": boolean; "model": string; "provider": string; };
+
export type SettingPetalDisabledData = { "dataChangePlugins": Array<string> | null; "globalPetalChanged": boolean; "globalPetalDisabled": boolean; "globalPetalEnabled": boolean; "globalPetalRevision": number; "reloadPlugins": Array<string> | null; "uninstallPlugins": Array<string> | null; "unloadPlugins": Array<string> | null; };
export type SettingPetalDisabledRequestInput = { "petalDisabled": boolean; };
@@ -2104,7 +2116,7 @@ export type SystemAPITokenRequestInput = { "token": string; };
export type SystemAccessAuthCodeRequestInput = { "accessAuthCode": string; };
-export type SystemAppConf = { "accessAuthCode": string; "ai": SettingAI | null; "api": SystemAPI | null; "appearance": SettingAppearance | null; "bazaar": SettingBazaar | null; "cloudRegion": number; "cookieKey": string; "dataIndexState": number; "editor": SettingEditor | null; "export": SettingExport | null; "fileTree": SettingFileTree | null; "flashcard": SettingFlashcard | null; "graph": SystemGraph | null; "keymap": { [key: string]: JSONValue } | null; "lang": string; "langs": Array<SystemLang | null> | null; "logLevel": string; "mcpOAuth": string; "notebookCrypto": SystemNotebookCrypto | null; "oidc": SystemOIDC | null; "onboarding": SystemOnboarding | null; "publish": SettingPublish | null; "readonly": boolean; "repo": SystemRepo | null; "search": SettingSearch | null; "secrets": SettingSecrets | null; "serverAddrs": Array<string> | null; "showChangelog": boolean; "snippet": SettingSnpt | null; "stat": SystemStat | null; "sync": SystemSync | null; "system": SystemSystem | null; "tag": SystemTag | null; "uiLayout": { [key: string]: JSONValue } | null; "userData": string; "variables": SettingVariables | null; };
+export type SystemAppConf = { "accessAuthCode": string; "ai": SettingAI | null; "api": SystemAPI | null; "appearance": SettingAppearance | null; "bazaar": SettingBazaar | null; "cloudRegion": number; "cookieKey": string; "dataIndexState": number; "editor": SettingEditor | null; "export": SettingExport | null; "fileTree": SettingFileTree | null; "flashcard": SettingFlashcard | null; "graph": SystemGraph | null; "keymap": { [key: string]: JSONValue } | null; "lang": string; "langs": Array<SystemLang | null> | null; "logLevel": string; "mcpOAuth": string; "notebookCrypto": SystemNotebookCrypto | null; "ocr": SettingOCR | null; "oidc": SystemOIDC | null; "onboarding": SystemOnboarding | null; "publish": SettingPublish | null; "readonly": boolean; "repo": SystemRepo | null; "search": SettingSearch | null; "secrets": SettingSecrets | null; "serverAddrs": Array<string> | null; "showChangelog": boolean; "snippet": SettingSnpt | null; "stat": SystemStat | null; "sync": SystemSync | null; "system": SystemSystem | null; "tag": SystemTag | null; "uiLayout": { [key: string]: JSONValue } | null; "userData": string; "variables": SettingVariables | null; };
export type SystemAppearanceData = { "appearance": SettingAppearance | null; };
@@ -2819,11 +2831,21 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": Array<AssetUnusedItem | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/api/asset/getOCRConfig": {
+ request: EmptyRequestInput;
+ response: { "code": 0; "data": OCRConfigData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/asset/getUnusedAssets": {
request: EmptyRequestInput;
response: { "code": 0; "data": Array<AssetUnusedItem | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "none";
};
+ "/api/asset/importOCRModels": {
+ request: ImportOCRModelsRequestInput;
+ response: { "code": 0; "data": OCRModel; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "multipart";
+ };
"/api/asset/insertCover": {
request: InsertCoverRequestInput;
response: { "code": 0; "data": AssetInsertCoverData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
@@ -2874,6 +2896,11 @@ export interface APIPOSTRoutes {
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
};
+ "/api/asset/setOCRConfig": {
+ request: SettingOCRInput;
+ response: { "code": 0; "data": SettingOCR; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ body: "json";
+ };
"/api/asset/statAsset": {
request: AssetPathRequestInput;
response: { "code": 0; "data": AssetStatData; "msg": string; } | { "code": -1 | 1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 1547da8b8a..ab51555b44 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -27,6 +27,8 @@ declare namespace Config {
accessAuthCode: string;
oidc: IOIDC;
ai: IAI;
+ /** 当前设备的本地 OCR 提供商和模型选择;切换后保留已有识别文本 */
+ ocr: {provider: string; model: string; auto: boolean};
api: IAPI;
appearance: IAppearance;
bazaar: IBazaar;
diff --git a/app/stage/ocr/ONNXRUNTIME-LICENSE b/app/stage/ocr/ONNXRUNTIME-LICENSE
new file mode 100644
index 0000000000..48bc6bb499
--- /dev/null
+++ b/app/stage/ocr/ONNXRUNTIME-LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/app/stage/ocr/ONNXRUNTIME-THIRD-PARTY-NOTICES.txt b/app/stage/ocr/ONNXRUNTIME-THIRD-PARTY-NOTICES.txt
new file mode 100644
index 0000000000..fbd9f9a95f
--- /dev/null
+++ b/app/stage/ocr/ONNXRUNTIME-THIRD-PARTY-NOTICES.txt
@@ -0,0 +1,6121 @@
+THIRD PARTY SOFTWARE NOTICES AND INFORMATION
+
+Do Not Translate or Localize
+
+This software incorporates material from third parties. Microsoft makes certain
+open source code available at http://3rdpartysource.microsoft.com, or you may
+send a check or money order for US $5.00, including the product name, the open
+source component name, and version number, to:
+
+Source Code Compliance Team
+Microsoft Corporation
+One Microsoft Way
+Redmond, WA 98052
+USA
+
+Notwithstanding any other terms, you may reverse engineer this software to the
+extent required to debug changes to any libraries licensed under the GNU Lesser
+General Public License.
+
+_____
+
+Intel Math Kernel Library (Intel MKL)
+
+Intel Simplified Software License (Version April 2018)
+
+Copyright (c) 2018 Intel Corporation.
+
+Use and Redistribution. You may use and redistribute the software (the “Software”), without modification,
+provided the following conditions are met:
+
+* Redistributions must reproduce the above copyright notice and the following terms of use in the Software
+and in the documentation and/or other materials provided with the distribution.
+
+* Neither the name of Intel nor the names of its suppliers may be used to endorse or promote products
+derived from this Software without specific prior written permission.
+
+* No reverse engineering, decompilation, or disassembly of this Software is permitted.
+
+Limited patent license. Intel grants you a world-wide, royalty-free, non-exclusive license under patents it now
+or hereafter owns or controls to make, have made, use, import, offer to sell and sell (“Utilize”) this Software,
+but solely to the extent that any such patent is necessary to Utilize the Software alone. The patent license
+shall not apply to any combinations which include this software. No hardware per se is licensed hereunder.
+
+Third party and other Intel programs. “Third Party Programs” are the files listed in the “third-party-programs.txt”
+text file that is included with the Software and may include Intel programs under separate license terms.
+Third Party Programs, even if included with the distribution of the Materials, are governed by
+separate license terms and those license terms solely govern your use of those programs.
+
+DISCLAIMER. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
+INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. THIS SOFTWARE IS
+NOT INTENDED FOR USE IN SYSTEMS OR APPLICATIONS WHERE FAILURE OF THE SOFTWARE
+MAY CAUSE PERSONAL INJURY OR DEATH AND YOU AGREE THAT YOU ARE FULLY RESPONSIBLE FOR ANY
+CLAIMS, COSTS, DAMAGES, EXPENSES, AND ATTORNEYS’ FEES ARISING OUT OF ANY SUCH USE,
+EVEN IF ANY CLAIM ALLEGES THAT INTEL WAS NEGLIGENT REGARDING THE DESIGN OR MANUFACTURE OF
+THE MATERIALS.
+
+LIMITATION OF LIABILITY. IN NO EVENT WILL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+OF SUCH DAMAGE. YOU AGREE TO INDEMNIFY AND HOLD INTEL HARMLESS AGAINST ANY CLAIMS
+AND EXPENSES RESULTING FROM YOUR USE OR UNAUTHORIZED USE OF THE SOFTWARE.
+
+No support. Intel may make changes to the Software, at any time without notice, and is not obligated to
+support, update or provide training for the Software.
+
+Termination. Intel may terminate your right to use the Software in the event of your breach of this Agreement
+and you fail to cure the breach within a reasonable period of time.
+
+Feedback. Should you provide Intel with comments, modifications, corrections, enhancements or other input
+(“Feedback”) related to the Software Intel will be free to use, disclose, reproduce, license or otherwise
+distribute or exploit the Feedback in its sole discretion without any obligations or restrictions of any kind,
+including without limitation, intellectual property rights or licensing obligations.
+
+Compliance with laws. You agree to comply with all relevant laws and regulations governing your use,
+transfer, import or export (or prohibition thereof) of the Software.
+
+Governing law. All disputes will be governed by the laws of the United States of America and the State of
+Delaware without reference to conflict of law principles and subject to the exclusive jurisdiction of the state or
+federal courts sitting in the State of Delaware, and each party agrees that it submits to the personal
+jurisdiction and venue of those courts and waives any objections. The United Nations Convention on
+Contracts for the International Sale of Goods (1980) is specifically excluded and will not apply to the
+Software.
+
+*Other names and brands may be claimed as the property of others.
+
+_____
+
+protocolbuffers/protobuf
+
+Copyright 2008 Google Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Code generated by the Protocol Buffer compiler is owned by the owner
+of the input file used when generating it. This code is not
+standalone and requires a support library to be linked with it. This
+support library is itself covered by the above license.
+
+_____
+
+madler/zlib
+
+The deflate format used by zlib was defined by Phil Katz. The deflate and
+zlib specifications were written by L. Peter Deutsch. Thanks to all the
+people who reported problems and suggested various improvements in zlib; they
+are too numerous to cite here.
+
+Copyright notice:
+
+ (C) 1995-2017 Jean-loup Gailly and Mark Adler
+
+ This software is provided 'as-is', without any express or implied
+ warranty. In no event will the authors be held liable for any damages
+ arising from the use of this software.
+
+ Permission is granted to anyone to use this software for any purpose,
+ including commercial applications, and to alter it and redistribute it
+ freely, subject to the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+
+ 3. This notice may not be removed or altered from any source distribution.
+
+ Jean-loup Gailly Mark Adler
+
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign. The sources are provided for free but without
+warranty of any kind. The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes. Please read
+the FAQ for more information on the distribution of modified source versions.
+
+_____
+
+pybind/pybind11
+
+Copyright (c) 2016 Wenzel Jakob <[email protected]>, All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Please also refer to the file CONTRIBUTING.md, which clarifies licensing of
+external contributions to this project including patches, pull requests, etc.
+
+_____
+
+onnx
+Open Neural Network Exchange
+
+Copyright (c) Facebook, Inc. and Microsoft Corporation. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+Eigen
+
+MPL v2.0
+Mozilla Public License Version 2.0
+
+
+==================================
+
+1. Definitions
+
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
+
+_____
+
+intel/dnnl
+
+Copyright 2016-2018 Intel Corporation
+
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+sub-components:
+
+xbyak
+
+Copyright (c) 2007 MITSUNARI Shigeo. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+Neither the name of the copyright owner nor the names of its contributors may
+be used to endorse or promote products derived from this software without
+specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+Microsoft GSL
+
+Copyright (c) 2015 Microsoft Corporation. All rights reserved.
+
+This code is licensed under the MIT License (MIT).
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+_____
+
+Tensorflow
+
+Copyright 2018 The TensorFlow Authors. All rights reserved.
+
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction,
+and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by
+the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all
+other entities that control, are controlled by, or are under common
+control with that entity. For the purposes of this definition,
+"control" means (i) the power, direct or indirect, to cause the
+direction or management of such entity, whether by contract or
+otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity
+exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications,
+including but not limited to software source code, documentation
+source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical
+transformation or translation of a Source form, including but
+not limited to compiled object code, generated documentation,
+and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or
+Object form, made available under the License, as indicated by a
+copyright notice that is included in or attached to the work
+(an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object
+form, that is based on (or derived from) the Work and for which the
+editorial revisions, annotations, elaborations, or other modifications
+represent, as a whole, an original work of authorship. For the purposes
+of this License, Derivative Works shall not include works that remain
+separable from, or merely link (or bind by name) to the interfaces of,
+the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including
+the original version of the Work and any modifications or additions
+to that Work or Derivative Works thereof, that is intentionally
+submitted to Licensor for inclusion in the Work by the copyright owner
+or by an individual or Legal Entity authorized to submit on behalf of
+the copyright owner. For the purposes of this definition, "submitted"
+means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems,
+and issue tracking systems that are managed by, or on behalf of, the
+Licensor for the purpose of discussing and improving the Work, but
+excluding communication that is conspicuously marked or otherwise
+designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity
+on behalf of whom a Contribution has been received by Licensor and
+subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+this License, each Contributor hereby grants to You a perpetual,
+worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the
+Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+this License, each Contributor hereby grants to You a perpetual,
+worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+(except as stated in this section) patent license to make, have made,
+use, offer to sell, sell, import, and otherwise transfer the Work,
+where such license applies only to those patent claims licensable
+by such Contributor that are necessarily infringed by their
+Contribution(s) alone or by combination of their Contribution(s)
+with the Work to which such Contribution(s) was submitted. If You
+institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work
+or a Contribution incorporated within the Work constitutes direct
+or contributory patent infringement, then any patent licenses
+granted to You under this License for that Work shall terminate
+as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+Work or Derivative Works thereof in any medium, with or without
+modifications, and in Source or Object form, provided that You
+meet the following conditions:
+
+(a) You must give any other recipients of the Work or
+Derivative Works a copy of this License; and
+
+(b) You must cause any modified files to carry prominent notices
+stating that You changed the files; and
+
+(c) You must retain, in the Source form of any Derivative Works
+that You distribute, all copyright, patent, trademark, and
+attribution notices from the Source form of the Work,
+excluding those notices that do not pertain to any part of
+the Derivative Works; and
+
+(d) If the Work includes a "NOTICE" text file as part of its
+distribution, then any Derivative Works that You distribute must
+include a readable copy of the attribution notices contained
+within such NOTICE file, excluding those notices that do not
+pertain to any part of the Derivative Works, in at least one
+of the following places: within a NOTICE text file distributed
+as part of the Derivative Works; within the Source form or
+documentation, if provided along with the Derivative Works; or,
+within a display generated by the Derivative Works, if and
+wherever such third-party notices normally appear. The contents
+of the NOTICE file are for informational purposes only and
+do not modify the License. You may add Your own attribution
+notices within Derivative Works that You distribute, alongside
+or as an addendum to the NOTICE text from the Work, provided
+that such additional attribution notices cannot be construed
+as modifying the License.
+
+You may add Your own copyright statement to Your modifications and
+may provide additional or different license terms and conditions
+for use, reproduction, or distribution of Your modifications, or
+for any such Derivative Works as a whole, provided Your use,
+reproduction, and distribution of the Work otherwise complies with
+the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+any Contribution intentionally submitted for inclusion in the Work
+by You to the Licensor shall be under the terms and conditions of
+this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify
+the terms of any separate license agreement you may have executed
+with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+names, trademarks, service marks, or product names of the Licensor,
+except as required for reasonable and customary use in describing the
+origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+agreed to in writing, Licensor provides the Work (and each
+Contributor provides its Contributions) on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+implied, including, without limitation, any warranties or conditions
+of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+PARTICULAR PURPOSE. You are solely responsible for determining the
+appropriateness of using or redistributing the Work and assume any
+risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+whether in tort (including negligence), contract, or otherwise,
+unless required by applicable law (such as deliberate and grossly
+negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special,
+incidental, or consequential damages of any character arising as a
+result of this License or out of the use or inability to use the
+Work (including but not limited to damages for loss of goodwill,
+work stoppage, computer failure or malfunction, or any and all
+other commercial damages or losses), even if such Contributor
+has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+the Work or Derivative Works thereof, You may choose to offer,
+and charge a fee for, acceptance of support, warranty, indemnity,
+or other liability obligations and/or rights consistent with this
+License. However, in accepting such obligations, You may act only
+on Your own behalf and on Your sole responsibility, not on behalf
+of any other Contributor, and only if You agree to indemnify,
+defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason
+of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017, The TensorFlow Authors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+Microsoft Cognitive Toolkit (CNTK)
+
+Copyright (c) Microsoft Corporation. All rights reserved.
+
+MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
+merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+_____
+
+NumPy License
+
+Copyright (c) 2005, NumPy Developers
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+ Neither the name of the NumPy Developers nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+Pytorch / Caffe2
+
+From PyTorch:
+
+Copyright (c) 2016- Facebook, Inc (Adam Paszke)
+Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
+Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
+Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
+Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
+Copyright (c) 2011-2013 NYU (Clement Farabet)
+Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
+Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
+Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
+
+From Caffe2:
+
+Copyright (c) 2016-present, Facebook Inc. All rights reserved.
+
+All contributions by Facebook:
+Copyright (c) 2016 Facebook Inc.
+
+All contributions by Google:
+Copyright (c) 2015 Google Inc.
+All rights reserved.
+
+All contributions by Yangqing Jia:
+Copyright (c) 2015 Yangqing Jia
+All rights reserved.
+
+All contributions from Caffe:
+Copyright(c) 2013, 2014, 2015, the respective contributors
+All rights reserved.
+
+All other contributions:
+Copyright(c) 2015, 2016 the respective contributors
+All rights reserved.
+
+Caffe2 uses a copyright model similar to Caffe: each contributor holds
+copyright over their contributions to Caffe2. The project versioning records
+all such contribution and copyright details. If a contributor wants to further
+mark their specific copyright on a particular contribution, they should
+indicate their copyright solely in the commit message of the change when it is
+committed. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
+ and IDIAP Research Institute nor the names of its contributors may be
+ used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+Caffe
+
+COPYRIGHT
+
+All contributions by the University of California:
+Copyright (c) 2014-2017 The Regents of the University of California (Regents)
+All rights reserved.
+
+All other contributions:
+Copyright (c) 2014-2017, the respective contributors
+All rights reserved.
+
+Caffe uses a shared copyright model: each contributor holds copyright over
+their contributions to Caffe. The project versioning records all such
+contribution and copyright details. If a contributor wants to further mark
+their specific copyright on a particular contribution, they should indicate
+their copyright solely in the commit message of the change when it is
+committed.
+
+LICENSE
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+CONTRIBUTION AGREEMENT
+
+By contributing to the BVLC/caffe repository through pull-request, comment,
+or otherwise, the contributor releases their content to the
+license and copyright terms herein.
+
+_____
+
+The LLVM Compiler Infrastructure
+
+==============================================================================
+LLVM Release License
+==============================================================================
+University of Illinois/NCSA
+Open Source License
+
+Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
+All rights reserved.
+
+Developed by:
+
+ LLVM Team
+
+ University of Illinois at Urbana-Champaign
+
+ http://llvm.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal with
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+ * Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimers.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimers in the
+ documentation and/or other materials provided with the distribution.
+
+ * Neither the names of the LLVM Team, University of Illinois at
+ Urbana-Champaign, nor the names of its contributors may be used to
+ endorse or promote products derived from this Software without specific
+ prior written permission.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
+SOFTWARE.
+
+==============================================================================
+Copyrights and Licenses for Third Party Software Distributed with LLVM:
+==============================================================================
+The LLVM software contains code written by third parties. Such software will
+have its own individual LICENSE.TXT file in the directory in which it appears.
+This file will describe the copyrights, license, and restrictions which apply
+to that code.
+
+The disclaimer of warranty in the University of Illinois Open Source License
+applies to all code in the LLVM Distribution, and nothing in any of the
+other licenses gives permission to use the names of the LLVM Team or the
+University of Illinois to endorse or promote products derived from this
+Software.
+
+The following pieces of software have additional or alternate copyrights,
+licenses, and/or restrictions:
+
+Program Directory
+------- ---------
+Google Test llvm/utils/unittest/googletest
+OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
+pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
+ARM contributions llvm/lib/Target/ARM/LICENSE.TXT
+md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
+
+_____
+
+google/benchmark
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+CONTRIBUTORS
+
+# People who have agreed to one of the CLAs and can contribute patches.
+# The AUTHORS file lists the copyright holders; this file
+# lists people. For example, Google employees are listed here
+# but not in AUTHORS, because Google holds the copyright.
+#
+# Names should be added to this file only after verifying that
+# the individual or the individual's organization has agreed to
+# the appropriate Contributor License Agreement, found here:
+#
+# https://developers.google.com/open-source/cla/individual
+# https://developers.google.com/open-source/cla/corporate
+#
+# The agreement for individuals can be filled out on the web.
+#
+# When adding J Random Contributor's name to this file,
+# either J's name or J's organization's name should be
+# added to the AUTHORS file, depending on whether the
+# individual or corporate CLA was used.
+#
+# Names should be added to this file as:
+# Name <email address>
+#
+# Please keep the list sorted.
+
+Albert Pretorius <[email protected]>
+Arne Beer <[email protected]>
+Billy Robert O'Neal III <[email protected]> <[email protected]>
+Christopher Seymour <[email protected]>
+David Coeurjolly <[email protected]>
+Deniz Evrenci <[email protected]>
+Dominik Czarnota <[email protected]>
+Eric Fiselier <[email protected]>
+Eugene Zhuk <[email protected]>
+Evgeny Safronov <[email protected]>
+Federico Ficarelli <[email protected]>
+Felix Homann <[email protected]>
+Ismael Jimenez Martinez <[email protected]>
+Jern-Kuan Leong <[email protected]>
+JianXiong Zhou <[email protected]>
+Joao Paulo Magalhaes <[email protected]>
+John Millikin <[email protected]>
+Jussi Knuuttila <[email protected]>
+Kai Wolf <[email protected]>
+Kishan Kumar <[email protected]>
+Kaito Udagawa <[email protected]>
+Matt Clarkson <[email protected]>
+Maxim Vafin <[email protected]>
+Nick Hutchinson <[email protected]>
+Oleksandr Sochka <[email protected]>
+Pascal Leroy <[email protected]>
+Paul Redmond <[email protected]>
+Pierre Phaneuf <[email protected]>
+Radoslav Yovchev <[email protected]>
+Raul Marin <[email protected]>
+Ray Glover <[email protected]>
+Robert Guo <[email protected]>
+Roman Lebedev <[email protected]>
+Shuo Chen <[email protected]>
+Tobias Ulvgård <[email protected]>
+Yixuan Qiu <[email protected]>
+Yusuke Suzuki <[email protected]>
+Zbigniew Skowron <[email protected]>
+
+AUTHORS
+
+# This is the official list of benchmark authors for copyright purposes.
+# This file is distinct from the CONTRIBUTORS files.
+# See the latter for an explanation.
+#
+# Names should be added to this file as:
+# Name or Organization <email address>
+# The email address is not required for organizations.
+#
+# Please keep the list sorted.
+
+Albert Pretorius <[email protected]>
+Arne Beer <[email protected]>
+Carto
+Christopher Seymour <[email protected]>
+David Coeurjolly <[email protected]>
+Deniz Evrenci <[email protected]>
+Dirac Research
+Dominik Czarnota <[email protected]>
+Eric Fiselier <[email protected]>
+Eugene Zhuk <[email protected]>
+Evgeny Safronov <[email protected]>
+Federico Ficarelli <[email protected]>
+Felix Homann <[email protected]>
+Google Inc.
+International Business Machines Corporation
+Ismael Jimenez Martinez <[email protected]>
+Jern-Kuan Leong <[email protected]>
+JianXiong Zhou <[email protected]>
+Joao Paulo Magalhaes <[email protected]>
+Jussi Knuuttila <[email protected]>
+Kaito Udagawa <[email protected]>
+Kishan Kumar <[email protected]>
+Matt Clarkson <[email protected]>
+Maxim Vafin <[email protected]>
+MongoDB Inc.
+Nick Hutchinson <[email protected]>
+Oleksandr Sochka <[email protected]>
+Paul Redmond <[email protected]>
+Radoslav Yovchev <[email protected]>
+Roman Lebedev <[email protected]>
+Shuo Chen <[email protected]>
+Steinar H. Gunderson <[email protected]>
+Stripe, Inc.
+Yixuan Qiu <[email protected]>
+Yusuke Suzuki <[email protected]>
+Zbigniew Skowron <[email protected]>
+
+_____
+
+HalideIR
+
+Copyright (c) 2016 HalideIR contributors
+Copyright (c) 2012-2014 MIT CSAIL, Google Inc., and other contributors
+HalideIR is derived from the Halide project.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+_____
+
+Distributed Machine Learning Common Codebase
+
+Copyright (c) 2015 by Contributors
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+_____
+
+DLPack: Open In Memory Tensor Structure
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 by Contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+HowardHinnant/date
+
+The source code in this project is released using the MIT License. There is no
+global license for the project because each file is licensed individually with
+different author names and/or dates.
+
+If you contribute to this project, please add your name to the license of each
+file you modify. If you have already contributed to this project and forgot to
+add your name to the license, please feel free to submit a new P/R to add your
+name to the license in each file you modified.
+
+For convenience, here is a copy of the MIT license found in each file except
+without author names or dates:
+
+The MIT License (MIT)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+
+FreeBSD: getopt.c file
+
+Copyright (c) 1987, 1993, 1994
+The Regents of the University of California. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+ 1. Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the University nor the names of its contributors
+may be used to endorse or promote products derived from this software
+without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGE.
+_____
+
+
+google/googletest
+
+Copyright 2008, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+G3log : Asynchronous logger with Dynamic Sinks
+
+This is free and unencumbered software released into the public domain.
+
+Anyone is free to copy, modify, publish, use, compile, sell, or
+distribute this software, either in source code form or as a compiled
+binary, for any purpose, commercial or non-commercial, and by any
+means.
+
+In jurisdictions that recognize copyright laws, the author or authors
+of this software dedicate any and all copyright interest in the
+software to the public domain. We make this dedication for the benefit
+of the public at large and to the detriment of our heirs and
+successors. We intend this dedication to be an overt act of
+relinquishment in perpetuity of all present and future rights to this
+software under copyright law.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+For more information, please refer to <http://unlicense.org/>
+_____
+
+Scikit-learn
+
+Copyright (c) 2007–2018 The scikit-learn developers.
+All rights reserved.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+ a. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ b. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ c. Neither the name of the Scikit-learn Developers nor the names of
+ its contributors may be used to endorse or promote products
+ derived from this software without specific prior written
+ permission.
+
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
+
+_____
+
+google/re2
+
+Copyright (c) 2009 The RE2 Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+_____
+onnx/onnx-tensorrt
+
+MIT License
+
+Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+Copyright (c) 2018 Open Neural Network Exchange
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+nvidia/cutlass
+
+Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+SPDX-License-Identifier: BSD-3-Clause
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+Boost
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+
+_____
+
+JDAI-CV/DNNLibrary
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [2019] [JD.com Inc. JD AI]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+_____
+
+google/flatbuffers
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2014 Google Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+_____
+
+google/glog
+
+Copyright (c) 2008, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+A function gettimeofday in utilities.cc is based on
+
+http://www.google.com/codesearch/p?hl=en#dR3YEbitojA/COPYING&q=GetSystemTimeAsFileTime%20license:bsd
+
+The license of this code is:
+
+Copyright (c) 2003-2008, Jouni Malinen <[email protected]> and contributors
+All Rights Reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the name(s) of the above-listed copyright holder(s) nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+abseil-cpp
+https://github.com/abseil/abseil-cpp
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ https://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+_____
+
+microsoft/wil
+
+MIT License
+
+Copyright (c) Microsoft Corporation. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE
+
+_____
+
+nlohmann/json
+
+MIT License
+
+Copyright (c) 2013-2019 Niels Lohmann
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+
+dcleblanc/SafeInt
+
+MIT License
+
+Copyright (c) 2018 Microsoft
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+Open MPI
+
+3-Clause BSD License
+
+Most files in this release are marked with the copyrights of the
+organizations who have edited them. The copyrights below are in no
+particular order and generally reflect members of the Open MPI core
+team who have contributed code to this release. The copyrights for
+code used under license from other parties are included in the
+corresponding files.
+
+Copyright (c) 2004-2010 The Trustees of Indiana University and Indiana
+ University Research and Technology
+ Corporation. All rights reserved.
+Copyright (c) 2004-2017 The University of Tennessee and The University
+ of Tennessee Research Foundation. All rights
+ reserved.
+Copyright (c) 2004-2010 High Performance Computing Center Stuttgart,
+ University of Stuttgart. All rights reserved.
+Copyright (c) 2004-2008 The Regents of the University of California.
+ All rights reserved.
+Copyright (c) 2006-2017 Los Alamos National Security, LLC. All rights
+ reserved.
+Copyright (c) 2006-2017 Cisco Systems, Inc. All rights reserved.
+Copyright (c) 2006-2010 Voltaire, Inc. All rights reserved.
+Copyright (c) 2006-2017 Sandia National Laboratories. All rights reserved.
+Copyright (c) 2006-2010 Sun Microsystems, Inc. All rights reserved.
+ Use is subject to license terms.
+Copyright (c) 2006-2017 The University of Houston. All rights reserved.
+Copyright (c) 2006-2009 Myricom, Inc. All rights reserved.
+Copyright (c) 2007-2017 UT-Battelle, LLC. All rights reserved.
+Copyright (c) 2007-2017 IBM Corporation. All rights reserved.
+Copyright (c) 1998-2005 Forschungszentrum Juelich, Juelich Supercomputing
+ Centre, Federal Republic of Germany
+Copyright (c) 2005-2008 ZIH, TU Dresden, Federal Republic of Germany
+Copyright (c) 2007 Evergrid, Inc. All rights reserved.
+Copyright (c) 2008 Chelsio, Inc. All rights reserved.
+Copyright (c) 2008-2009 Institut National de Recherche en
+ Informatique. All rights reserved.
+Copyright (c) 2007 Lawrence Livermore National Security, LLC.
+ All rights reserved.
+Copyright (c) 2007-2017 Mellanox Technologies. All rights reserved.
+Copyright (c) 2006-2010 QLogic Corporation. All rights reserved.
+Copyright (c) 2008-2017 Oak Ridge National Labs. All rights reserved.
+Copyright (c) 2006-2012 Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2009-2015 Bull SAS. All rights reserved.
+Copyright (c) 2010 ARM ltd. All rights reserved.
+Copyright (c) 2016 ARM, Inc. All rights reserved.
+Copyright (c) 2010-2011 Alex Brick . All rights reserved.
+Copyright (c) 2012 The University of Wisconsin-La Crosse. All rights
+ reserved.
+Copyright (c) 2013-2016 Intel, Inc. All rights reserved.
+Copyright (c) 2011-2017 NVIDIA Corporation. All rights reserved.
+Copyright (c) 2016 Broadcom Limited. All rights reserved.
+Copyright (c) 2011-2017 Fujitsu Limited. All rights reserved.
+Copyright (c) 2014-2015 Hewlett-Packard Development Company, LP. All
+ rights reserved.
+Copyright (c) 2013-2017 Research Organization for Information Science (RIST).
+ All rights reserved.
+Copyright (c) 2017-2018 Amazon.com, Inc. or its affiliates. All Rights
+ reserved.
+Copyright (c) 2018 DataDirect Networks. All rights reserved.
+Copyright (c) 2018-2019 Triad National Security, LLC. All rights reserved.
+
+$COPYRIGHT$
+
+Additional copyrights may follow
+
+$HEADER$
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+- Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer listed
+ in this license in the documentation and/or other materials
+ provided with the distribution.
+
+- Neither the name of the copyright holders nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+The copyright holders provide no reassurances that the source code
+provided does not infringe any patent, copyright, or any other
+intellectual property rights of third parties. The copyright holders
+disclaim any liability to any recipient for claims brought against
+recipient by any third party for infringement of that parties
+intellectual property rights.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+The Android Open Source Project
+
+Copyright (C) 2017 The Android Open Source Project
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+
+------
+
+libprotobuf-mutator
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ -----
+
+ openucx/ucx
+ https://github.com/openucx/ucx
+
+ Copyright (c) 2014-2015 UT-Battelle, LLC. All rights reserved.
+ Copyright (C) 2014-2020 Mellanox Technologies Ltd. All rights reserved.
+ Copyright (C) 2014-2015 The University of Houston System. All rights reserved.
+ Copyright (C) 2015 The University of Tennessee and The University
+ of Tennessee Research Foundation. All rights reserved.
+ Copyright (C) 2016-2020 ARM Ltd. All rights reserved.
+ Copyright (c) 2016 Los Alamos National Security, LLC. All rights reserved.
+ Copyright (C) 2016-2020 Advanced Micro Devices, Inc. All rights reserved.
+ Copyright (C) 2019 UChicago Argonne, LLC. All rights reserved.
+ Copyright (c) 2018-2020 NVIDIA CORPORATION. All rights reserved.
+ Copyright (C) 2020 Huawei Technologies Co., Ltd. All rights reserved.
+ Copyright (C) 2016-2020 Stony Brook University. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ 3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ -----
+
+ From PyTorch:
+
+ Copyright (c) 2016- Facebook, Inc (Adam Paszke)
+ Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
+ Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
+ Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
+ Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
+ Copyright (c) 2011-2013 NYU (Clement Farabet)
+ Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
+ Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
+ Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
+
+ From Caffe2:
+
+ Copyright (c) 2016-present, Facebook Inc. All rights reserved.
+
+ All contributions by Facebook:
+ Copyright (c) 2016 Facebook Inc.
+
+ All contributions by Google:
+ Copyright (c) 2015 Google Inc.
+ All rights reserved.
+
+ All contributions by Yangqing Jia:
+ Copyright (c) 2015 Yangqing Jia
+ All rights reserved.
+
+ All contributions from Caffe:
+ Copyright(c) 2013, 2014, 2015, the respective contributors
+ All rights reserved.
+
+ All other contributions:
+ Copyright(c) 2015, 2016 the respective contributors
+ All rights reserved.
+
+ Caffe2 uses a copyright model similar to Caffe: each contributor holds
+ copyright over their contributions to Caffe2. The project versioning records
+ all such contribution and copyright details. If a contributor wants to further
+ mark their specific copyright on a particular contribution, they should
+ indicate their copyright solely in the commit message of the change when it is
+ committed.
+
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ 3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
+ and IDIAP Research Institute nor the names of its contributors may be
+ used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+ mpi4py
+ https://github.com/mpi4py/mpi4py/
+
+ =======================
+ LICENSE: MPI for Python
+ =======================
+
+ :Author: Lisandro Dalcin
+ :Contact: [email protected]
+
+
+ Copyright (c) 2019, Lisandro Dalcin.
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+_____
+huggingface/transformers
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+_____
+msgpack/msgpack-python
+
+Copyright (C) 2008-2011 INADA Naoki <[email protected]>
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+_____
+lanpa/tensorboardX
+
+MIT License
+
+Copyright (c) 2017 Tzu-Wei Huang
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+_____
+tensorflow/tensorboard
+
+Copyright 2017 The TensorFlow Authors. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017, The TensorFlow Authors.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+_____
+
+cerberus
+
+Cerberus is a lightweight and extensible data validation library for Python.
+
+ISC License
+
+Copyright (c) 2012-2016 Nicola Iarocci.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
+_____
+
+MurmurHash3
+
+MIT license
+
+https://github.com/aappleby/smhasher
+
+SMHasher is a test suite designed to test the distribution, collision, and
+performance properties of non-cryptographic hash functions.
+This is the home for the MurmurHash family of hash functions along with the
+SMHasher test suite used to verify them.
+SMHasher is released under the MIT license.
+All MurmurHash versions are public domain software, and the author disclaims all copyright to their code.
+
+_____
+
+gtest-ios-framework
+
+https://github.com/mestevens/gtest-ios-framework
+
+Copyright (c) 2013 Matthew Stevens
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+_____
+
+DLPack
+
+https://github.com/dmlc/dlpack
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2017 by Contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+emsdk
+
+MIT/Expat license
+
+https://github.com/emscripten-core/emsdk
+
+Copyright (c) 2018 Emscripten authors (see AUTHORS in Emscripten)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+----------------------------------------------------------------------------
+
+This is the MIT/Expat License. For more information see:
+
+1. http://www.opensource.org/licenses/mit-license.php
+
+2. http://en.wikipedia.org/wiki/MIT_License
+
+_____
+
+coremltools
+
+BSD-3-Clause License
+
+https://github.com/apple/coremltools
+
+Copyright (c) 2020, Apple Inc. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+© 2021 GitHub, Inc.
+
+_____
+
+react-native
+
+MIT License
+
+https://github.com/facebook/react-native
+
+Copyright (c) Facebook, Inc. and its affiliates.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+
+pytorch/cpuinfo
+
+BSD 2-Clause "Simplified" License
+
+https://github.com/pytorch/cpuinfo
+
+Copyright (c) 2019 Google LLC
+Copyright (c) 2017-2018 Facebook Inc.
+Copyright (C) 2012-2017 Georgia Institute of Technology
+Copyright (C) 2010-2012 Marat Dukhan
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+SQLite Is Public Domain
+
+All of the code and documentation in SQLite has been dedicated to the public
+domain by the authors. All code authors, and representatives of the companies
+they work for, have signed affidavits dedicating their contributions to the
+public domain and originals of those signed affidavits are stored in a firesafe
+at the main offices of Hwaci. Anyone is free to copy, modify, publish, use,
+compile, sell, or distribute the original SQLite code, either in source code
+form or as a compiled binary, for any purpose, commercial or non-commercial,
+and by any means.
+
+The previous paragraph applies to the deliverable code and documentation in
+SQLite - those parts of the SQLite library that you actually bundle and ship
+with a larger application. Some scripts used as part of the build process (for
+example the "configure" scripts generated by autoconf) might fall under other
+open-source licenses. Nothing from these build scripts ever reaches the final
+deliverable SQLite library, however, and so the licenses associated with those
+scripts should not be a factor in assessing your rights to copy and use the
+SQLite library.
+
+All of the deliverable code in SQLite has been written from scratch. No code
+has been taken from other projects or from the open internet. Every line of
+code can be traced back to its original author, and all of those authors have
+public domain dedications on file. So the SQLite code base is clean and is
+uncontaminated with licensed code from other projects.
+
+_____
+
+google/XNNPACK
+
+BSD License
+
+For XNNPACK software
+
+Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
+Copyright 2019 Google LLC
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ * Neither the name Facebook nor the names of its contributors may be used to
+ endorse or promote products derived from this software without specific
+ prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+google/sentencepiece, https://github.com/google/sentencepiece
+(included when statically linked with onnxruntime-extensions)
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+dlfcn-win32/dlfcn-win32 is licensed under the MIT License
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+_____
+
+The Python Imaging Library (PIL) is
+
+ Copyright © 1997-2011 by Secret Labs AB
+ Copyright © 1995-2011 by Fredrik Lundh
+
+Pillow is the friendly PIL fork. It is
+
+ Copyright © 2010-2023 by Alex Clark and contributors
+
+Like PIL, Pillow is licensed under the open source HPND License:
+
+By obtaining, using, and/or copying this software and/or its associated
+documentation, you agree that you have read, understood, and will comply
+with the following terms and conditions:
+
+Permission to use, copy, modify, and distribute this software and its
+associated documentation for any purpose and without fee is hereby granted,
+provided that the above copyright notice appears in all copies, and that
+both that copyright notice and this permission notice appear in supporting
+documentation, and that the name of Secret Labs AB or the author not be
+used in advertising or publicity pertaining to distribution of the software
+without specific, written prior permission.
+
+SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
+IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL,
+INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
+_____
+
+openssl/openssl, https://github.com/openssl/openssl
+
+ Apache License
+ Version 2.0, January 2004
+ https://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+_____
+
+Tencent/rapidjson, https://github.com/Tencent/rapidjson
+
+Tencent is pleased to support the open source community by making RapidJSON available.
+
+Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+
+If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License.
+If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license.
+A copy of the MIT License is included in this file.
+
+Other dependencies and licenses:
+
+Open Source Software Licensed Under the BSD License:
+--------------------------------------------------------------------
+
+The msinttypes r29
+Copyright (c) 2006-2013 Alexander Chemeris
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+Open Source Software Licensed Under the JSON License:
+--------------------------------------------------------------------
+
+json.org
+Copyright (c) 2002 JSON.org
+All Rights Reserved.
+
+JSON_checker
+Copyright (c) 2002 JSON.org
+All Rights Reserved.
+
+
+Terms of the JSON License:
+---------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+
+Terms of the MIT License:
+--------------------------------------------------------------------
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+_____
+
+boostorg/boost, https://github.com/boostorg/boost
+
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
+
+_____
+
+libb64/libb64, https://github.com/libb64/libb64
+
+Copyright-Only Dedication (based on United States law) or Public Domain Certification
+
+The person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below.
+
+A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain.
+
+Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work.
+
+Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived.
+
+_____
+
+posix pthread library, https://sourceforge.net/projects/pthreads4w
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+_____
+
+Triton Inference Server & Client, https://github.com/triton-inference-server
+
+Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of NVIDIA CORPORATION nor the names of its
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+microsoft/mimalloc, https://github.com/microsoft/mimalloc
+
+MIT License
+
+Copyright (c) 2018-2021 Microsoft Corporation, Daan Leijen
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+_____
+
+TensorFlow.js
+
+https://github.com/tensorflow/tfjs
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+——
+
+curl/curl
+
+https://github.com/curl
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (C) Daniel Stenberg, <[email protected]>, and many
+contributors, see the THANKS file.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright
+notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall not
+be used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization of the copyright holder.
+
+_____
+
+Intel neural-compressor
+
+https://github.com/intel/neural-compressor
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ ============================================================================
+
+ Copyright 2016-2019 Intel Corporation
+ Copyright 2018 YANDEX LLC
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ This distribution includes third party software ("third party programs").
+ This third party software, even if included with the distribution of
+ the Intel software, may be governed by separate license terms, including
+ without limitation, third party license terms, other Intel software license
+ terms, and open source software license terms. These separate license terms
+ govern your use of the third party programs as set forth in the
+ "THIRD-PARTY-PROGRAMS" file.
+
+_____
+
+FlashAttention, https://github.com/Dao-AILab/flash-attention
+
+BSD 3-Clause License
+
+Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+* Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+neural-speed
+
+https://github.com/intel/neural-speed
+
+ Apache License
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ ============================================================================
+
+ Copyright 2016-2019 Intel Corporation
+ Copyright 2018 YANDEX LLC
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ This distribution includes third party software ("third party programs").
+ This third party software, even if included with the distribution of
+ the Intel software, may be governed by separate license terms, including
+ without limitation, third party license terms, other Intel software license
+ terms, and open source software license terms. These separate license terms
+ govern your use of the third party programs as set forth in the
+ "THIRD-PARTY-PROGRAMS" file.
+
+_____
+
+dawn
+
+https://dawn.googlesource.com/dawn
+
+ BSD 3-Clause License
+
+ Copyright 2017-2023 The Dawn & Tint Authors
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ 2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+ 3. Neither the name of the copyright holder nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+_____
+
+KleidiAI
+
+https://gitlab.arm.com/kleidi/kleidiai
+
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+Copyright 2024-2025 Arm Limited and/or its affiliates <[email protected]>
+
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/app/stage/ocr/PADDLEOCR-LICENSE b/app/stage/ocr/PADDLEOCR-LICENSE
new file mode 100644
index 0000000000..430edfa0cf
--- /dev/null
+++ b/app/stage/ocr/PADDLEOCR-LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index ef5fd8494c..93c6bbe75f 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -17,6 +17,7 @@
package api
import (
+ "context"
"encoding/json"
"fmt"
"net/http"
@@ -32,7 +33,6 @@ import (
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/model"
- "github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -108,7 +108,7 @@ var getImageOCRText = contractHandler(apicontract.GetImageOCRText, func(c *gin.C
path := *request.Path
// 加密笔记本的资源不参与全局 OCR(OCR 文本存在全局 data/assets/ocr-texts.json)
- if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
+ if model.IsEncryptedOCRAsset(path) {
return apicontract.Success(apicontract.AssetTextData{Text: ""})
}
@@ -122,27 +122,22 @@ var setImageOCRText = contractHandler(apicontract.SetImageOCRText, func(c *gin.C
text := request.Text
// 加密笔记本的资源不参与全局 OCR
- if absPath, absErr := model.GetAssetAbsPathInBox(path, ""); absErr == nil && model.IsEncryptedAssetPath(absPath) {
+ if model.IsEncryptedOCRAsset(path) {
return apicontract.Success(apicontract.Null{})
}
- util.SetAssetText(path, text)
-
- // 刷新 OCR 结果到数据库
- util.NodeOCRQueueLock.Lock()
- defer util.NodeOCRQueueLock.Unlock()
- for _, id := range util.NodeOCRQueue {
- sql.IndexNodeQueue(id)
- }
- util.NodeOCRQueue = nil
+ model.SetOCRAssetText(path, text)
return apicontract.Success(apicontract.Null{})
})
var ocr = contractHandler(apicontract.AssetOCR, func(c *gin.Context, request apicontract.AssetPathRequest) apicontract.Response[apicontract.AssetOCRData] {
- path := request.Path
+ path := strings.SplitN(request.Path, "#", 2)[0]
// 加密笔记本的资源不参与全局 OCR
+ if model.IsEncryptedOCRAsset(path) {
+ return apicontract.FailureWithTimeout[apicontract.AssetOCRData](-1, model.Conf.Language(380), 3000)
+ }
absPath, err := model.GetAssetAbsPathInBox(path, "")
if err != nil {
return apicontract.Failure[apicontract.AssetOCRData](-1, err.Error())
@@ -154,7 +149,9 @@ var ocr = contractHandler(apicontract.AssetOCR, func(c *gin.Context, request api
return apicontract.Failure[apicontract.AssetOCRData](-1, err.Error())
}
- ocrJSON, err := util.OcrAsset(path)
+ ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute)
+ defer cancel()
+ ocrJSON, err := model.OCRAsset(ctx, path)
if nil != err {
return apicontract.FailureWithTimeout[apicontract.AssetOCRData](-1, err.Error(), 7000)
}
diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.go
new file mode 100644
index 0000000000..83fc97ea99
--- /dev/null
+++ b/kernel/api/contract_ocr_test.go
@@ -0,0 +1,286 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "image"
+ "image/png"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractOCREncryptedAssetAliases(t *testing.T) {
+ setupAssetContractWorkspace(t)
+ const boxID = "20261001010000-abcdefg"
+ directory := filepath.Join(util.DataDir, boxID, ".siyuan")
+ if err := os.MkdirAll(directory, 0755); err != nil {
+ t.Fatal(err)
+ }
+ box := conf.NewBoxConf()
+ box.Encrypted = true
+ content, err := json.Marshal(box)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(directory, "conf.json"), content, 0600); err != nil {
+ t.Fatal(err)
+ }
+ const path = "assets/missing-encrypted.png"
+ util.SetAssetText(path, "ordinary text")
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ engine := gin.New()
+ engine.POST("/api/asset/getImageOCRText", getImageOCRText)
+ engine.POST("/api/asset/setImageOCRText", setImageOCRText)
+ engine.POST("/api/asset/ocr", ocr)
+ for _, suffix := range []string{"?box=" + boxID, "?box=" + boxID + "#fragment"} {
+ for _, route := range []string{"getImageOCRText", "setImageOCRText", "ocr"} {
+ body, _ := json.Marshal(map[string]string{"path": path + suffix, "text": "private text"})
+ recorder := httptest.NewRecorder()
+ url := "/api/asset/" + route
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", url, bytes.NewReader(body)))
+ requireAPIContract(t, "POST", url, recorder)
+ var response struct {
+ Code int
+ Data struct{ Text string }
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Data.Text != "" || (route == "ocr" && response.Code == 0) {
+ t.Fatalf("encrypted OCR alias: %s, %v", recorder.Body.String(), err)
+ }
+ if util.GetAssetText(path) != "ordinary text" {
+ t.Fatal("encrypted OCR write changed shared text")
+ }
+ }
+ }
+}
+
+func TestAPIContractOCRPermissions(t *testing.T) {
+ setupAssetContractWorkspace(t)
+ previousReadOnly := util.ReadOnly
+ t.Cleanup(func() { util.ReadOnly = previousReadOnly })
+ for _, route := range []struct {
+ path string
+ write bool
+ handler gin.HandlerFunc
+ }{
+ {"/api/asset/getOCRConfig", false, getOCRConfig},
+ {"/api/asset/setOCRConfig", true, setOCRConfig},
+ {"/api/asset/importOCRModels", true, importOCRModels},
+ } {
+ for _, role := range []model.Role{model.RoleReader, model.RoleEditor, model.RoleAdministrator} {
+ for _, readonly := range []bool{false, true} {
+ util.ReadOnly = readonly
+ called := false
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role) })
+ handlers := []gin.HandlerFunc{model.CheckAuth, model.CheckAdminRole}
+ if route.write {
+ handlers = append(handlers, model.CheckReadonly)
+ }
+ handlers = append(handlers, func(c *gin.Context) { called = true; route.handler(c) })
+ engine.POST(route.path, handlers...)
+ engine.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", route.path, strings.NewReader(`{}`)))
+ if called != (role == model.RoleAdministrator && (!readonly || !route.write)) {
+ t.Fatalf("unexpected authorization: %s, %v, readonly=%v, called=%v", route.path, role, readonly, called)
+ }
+ }
+ }
+ }
+}
+
+func TestAPIContractOCRNativeImportAndHeadlessRecognition(t *testing.T) {
+ models := os.Getenv("SIYUAN_OCR_TEST_ASSETS")
+ if models == "" || os.Getenv("SIYUAN_OCR_TEST_LIBRARY") == "" {
+ t.Skip("native OCR resources are not configured")
+ }
+ assets := setupAssetContractWorkspace(t)
+ previousWorking, previousTemp, previousConf := util.WorkingDir, util.TempDir, util.ConfDir
+ util.WorkingDir = filepath.Dir(filepath.Dir(filepath.Dir(models)))
+ util.TempDir, util.ConfDir = t.TempDir(), t.TempDir()
+ t.Cleanup(func() { util.WorkingDir, util.TempDir, util.ConfDir = previousWorking, previousTemp, previousConf })
+ model.Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true}
+ engine := gin.New()
+ engine.POST("/api/asset/importOCRModels", importOCRModels)
+ engine.POST("/api/asset/ocr", ocr)
+ upload := func(invalid bool) apicontract.OCRModel {
+ t.Helper()
+ var body bytes.Buffer
+ writer := multipart.NewWriter(&body)
+ for field, name := range map[string]string{"detector": "det/inference.onnx", "detectorConfig": "det/inference.yml", "recognizer": "rec/inference.onnx", "recognizerConfig": "rec/inference.yml"} {
+ part, err := writer.CreateFormFile(field, "../../untrusted-"+filepath.Base(name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if invalid && field == "recognizer" {
+ _, err = part.Write([]byte("invalid ONNX"))
+ } else {
+ file, openErr := os.Open(filepath.Join(models, "tiny", filepath.FromSlash(name)))
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ _, err = io.Copy(part, file)
+ file.Close()
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest("POST", "/api/asset/importOCRModels", &body)
+ request.Header.Set("Content-Type", writer.FormDataContentType())
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, request)
+ if request.MultipartForm != nil {
+ defer request.MultipartForm.RemoveAll()
+ }
+ requireAPIContract(t, "POST", request.URL.Path, recorder)
+ var response struct {
+ Code int
+ Data apicontract.OCRModel
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if (response.Code != 0) != invalid {
+ t.Fatalf("import: %s", recorder.Body.String())
+ }
+ return response.Data
+ }
+ imported := upload(false)
+ if len(imported.ID) != 64 || imported.BuiltIn {
+ t.Fatalf("invalid model result: %+v", imported)
+ }
+ if duplicate := upload(false); duplicate.ID != imported.ID {
+ t.Fatal("duplicate upload changed model identity")
+ }
+ if err := model.Conf.SetOCR(conf.OCR{Provider: "paddleocr", Model: imported.ID, Auto: true}); err != nil {
+ t.Fatal(err)
+ }
+ file, err := os.Create(filepath.Join(assets, "headless.png"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = png.Encode(file, image.NewRGBA(image.Rect(0, 0, 100, 100))); err != nil {
+ t.Fatal(err)
+ }
+ file.Close()
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/api/asset/ocr", strings.NewReader(`{"path":"assets/headless.png"}`)))
+ requireAPIContract(t, "POST", "/api/asset/ocr", recorder)
+ var result struct {
+ Code int
+ Data apicontract.AssetOCRData
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.Code != 0 || result.Data.OCRJSON == nil {
+ t.Fatalf("headless API: %s, %v", recorder.Body.String(), err)
+ }
+ if !util.ExistsAssetText("assets/headless.png") {
+ t.Fatal("successful empty result was not saved")
+ }
+ t.Cleanup(func() { util.RemoveAssetText("assets/headless.png") })
+ upload(true)
+ entries, err := os.ReadDir(filepath.Join(util.DataDir, "ocr", "models"))
+ if err != nil || len(entries) != 1 {
+ t.Fatalf("invalid import published files: %v, %v", entries, err)
+ }
+ entries, err = os.ReadDir(util.TempDir)
+ if err != nil || len(entries) != 0 {
+ t.Fatalf("import leaked staging files: %v, %v", entries, err)
+ }
+}
+
+func TestAPIContractOCRSettings(t *testing.T) {
+ setupAssetContractWorkspace(t)
+ previousConfDir := util.ConfDir
+ util.ConfDir = t.TempDir()
+ t.Cleanup(func() { util.ConfDir = previousConfDir })
+ engine := gin.New()
+ engine.POST("/api/asset/getOCRConfig", getOCRConfig)
+ engine.POST("/api/asset/setOCRConfig", setOCRConfig)
+ get := httptest.NewRecorder()
+ engine.ServeHTTP(get, httptest.NewRequest("POST", "/api/asset/getOCRConfig", strings.NewReader(`{}`)))
+ requireAPIContract(t, "POST", "/api/asset/getOCRConfig", get)
+ var result struct{ Data apicontract.OCRConfigData }
+ if err := json.Unmarshal(get.Body.Bytes(), &result); err != nil {
+ t.Fatal(err)
+ }
+ if result.Data.Config.Provider != "tesseract" || !result.Data.Config.Auto || len(result.Data.Models) != 2 || len(result.Data.Providers) != 2 {
+ t.Fatalf("unexpected defaults: %+v", result.Data)
+ }
+ path := "assets/preserved.png"
+ util.SetAssetText(path, "existing text")
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ for _, test := range []struct {
+ body string
+ success bool
+ }{
+ {`{"provider":"tesseract","model":"tiny","auto":false}`, true},
+ {`{"provider":"unknown","model":"tiny","auto":true}`, false},
+ {`{"provider":"paddleocr","model":"../../outside","auto":true}`, false},
+ {`{"provider":"tesseract","model":"tiny","auto":"false"}`, false},
+ {`{"provider":"tesseract","model":"tiny"}`, false},
+ } {
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setOCRConfig", strings.NewReader(test.body)))
+ requireAPIContract(t, "POST", "/api/asset/setOCRConfig", recorder)
+ var response struct{ Code int }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if (response.Code == 0) != test.success {
+ t.Fatalf("body=%s response=%s", test.body, recorder.Body.String())
+ }
+ if util.GetAssetText(path) != "existing text" {
+ t.Fatal("configuration update changed existing OCR text")
+ }
+ }
+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var saved struct {
+ OCR conf.OCR `json:"ocr"`
+ }
+ if err = json.Unmarshal(data, &saved); err != nil {
+ t.Fatal(err)
+ }
+ if saved.OCR.Auto || saved.OCR.Model != "tiny" {
+ t.Fatalf("settings were not persisted: %+v", saved.OCR)
+ }
+}
+
+func TestAPIContractOCRFailurePreservesText(t *testing.T) {
+ assets := setupAssetContractWorkspace(t)
+ path := "assets/failure.png"
+ if err := os.WriteFile(filepath.Join(assets, "failure.png"), []byte("invalid image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ model.Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "small"}
+ util.SetAssetText(path, "previous result")
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ engine := gin.New()
+ engine.POST("/api/asset/ocr", ocr)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/ocr", strings.NewReader(`{"path":"assets/failure.png"}`)))
+ requireAPIContract(t, "POST", "/api/asset/ocr", recorder)
+ var response struct{ Code int }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ if response.Code == 0 || util.GetAssetText(path) != "previous result" {
+ t.Fatalf("failed OCR replaced text: %s", recorder.Body.String())
+ }
+}
diff --git a/kernel/api/ocr.go b/kernel/api/ocr.go
new file mode 100644
index 0000000000..08aee48428
--- /dev/null
+++ b/kernel/api/ocr.go
@@ -0,0 +1,57 @@
+package api
+
+import (
+ "context"
+ "mime/multipart"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+var getOCRConfig = contractHandler(apicontract.GetOCRConfig, func(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.OCRConfigData] {
+ value := model.Conf.GetOCR()
+ models := []apicontract.OCRModel{}
+ for _, id := range model.OCRModels() {
+ models = append(models, ocrModelPayload(id))
+ }
+ providers := []apicontract.OCRProviderState{}
+ for _, id := range []string{"tesseract", "paddleocr"} {
+ providers = append(providers, apicontract.OCRProviderState{ID: id, Available: model.OCRProviderAvailable(id)})
+ }
+ return apicontract.Success(apicontract.OCRConfigData{Config: apicontract.SettingOCR(value), Providers: providers, Models: models})
+})
+
+func ocrModelPayload(id string) apicontract.OCRModel {
+ name := id
+ if id == "tiny" {
+ name = "PP-OCRv6 Tiny"
+ } else if id == "small" {
+ name = "PP-OCRv6 Small"
+ } else {
+ name = "PP-OCRv6 " + strings.ToUpper(id[:8])
+ }
+ return apicontract.OCRModel{ID: id, Name: name, BuiltIn: id == "tiny" || id == "small"}
+}
+
+var setOCRConfig = contractHandler(apicontract.SetOCRConfig, func(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {
+ if err := model.Conf.SetOCR(conf.OCR(request)); err != nil {
+ return apicontract.Failure[apicontract.SettingOCR](-1, err.Error())
+ }
+ util.BroadcastByType("main", "setConf", 0, "", model.Conf)
+ return apicontract.Success(request)
+})
+
+var importOCRModels = contractHandler(apicontract.ImportOCRModels, func(c *gin.Context, request apicontract.ImportOCRModelsRequest) apicontract.Response[apicontract.OCRModel] {
+ ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute)
+ defer cancel()
+ id, err := model.ImportOCRModels(ctx, []*multipart.FileHeader{request.Detector, request.DetectorConfig, request.Recognizer, request.RecognizerConfig})
+ if err != nil {
+ return apicontract.Failure[apicontract.OCRModel](-1, err.Error())
+ }
+ return apicontract.Success(ocrModelPayload(id))
+})
diff --git a/kernel/api/router.go b/kernel/api/router.go
index 48a9653679..b8dcd8a0b0 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -423,6 +423,9 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/asset/getImageOCRText", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, getImageOCRText)
ginServer.Handle("POST", "/api/asset/setImageOCRText", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setImageOCRText)
ginServer.Handle("POST", "/api/asset/ocr", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, ocr)
+ ginServer.Handle("POST", "/api/asset/getOCRConfig", model.CheckAuth, model.CheckAdminRole, getOCRConfig)
+ ginServer.Handle("POST", "/api/asset/setOCRConfig", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setOCRConfig)
+ ginServer.Handle("POST", "/api/asset/importOCRModels", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, importOCRModels)
ginServer.Handle("POST", "/api/asset/fullReindexAssetContent", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, fullReindexAssetContent)
ginServer.Handle("POST", "/api/asset/statAsset", model.CheckAuth, model.CheckAdminRole, statAsset)
diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.go
index 34f2228258..3750efd7d1 100644
--- a/kernel/apicontract/asset.go
+++ b/kernel/apicontract/asset.go
@@ -82,7 +82,7 @@ type AssetTextData struct {
Text string `json:"text"`
}
-// AssetOCRData 的列名来自识别工具的 TSV 表头,单元格均为文本。
+// AssetOCRData 的列名沿用 Tesseract TSV 表头,所有提供商的单元格均为文本。
type AssetOCRData struct {
Text string `json:"text"`
OCRJSON []map[string]string `json:"ocrJSON"`
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index d0beec481e..bd32328bfc 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -845,7 +845,13 @@ var StatAsset = define[AssetPathRequest, AssetStatData]("statAsset", "/api/asset
var FullReindexAssetContent = define[EmptyRequest, Null]("fullReindexAssetContent", "/api/asset/fullReindexAssetContent", NoBody, ResponseOptions{}, "POST")
var GetImageOCRText = define[AssetOCRTextRequest, AssetTextData]("getImageOCRText", "/api/asset/getImageOCRText", JSONBody, ResponseOptions{}, "POST")
var SetImageOCRText = define[SetAssetOCRTextRequest, Null]("setImageOCRText", "/api/asset/setImageOCRText", JSONBody, ResponseOptions{}, "POST")
+
+// AssetOCR 始终使用当前设备选择的提供商,内核可在无界面的环境中识别。
+// 不自动回退到另一提供商;取消、模型或推理错误不覆盖已有文本,加密笔记本不参与 OCR。
var AssetOCR = define[AssetPathRequest, AssetOCRData]("ocr", "/api/asset/ocr", JSONBody, ResponseOptions{}, "POST")
+var GetOCRConfig = define[EmptyRequest, OCRConfigData]("getOCRConfig", "/api/asset/getOCRConfig", JSONBody, ResponseOptions{}, "POST")
+var SetOCRConfig = define[SettingOCR, SettingOCR]("setOCRConfig", "/api/asset/setOCRConfig", JSONBody, ResponseOptions{}, "POST")
+var ImportOCRModels = define[ImportOCRModelsRequest, OCRModel]("importOCRModels", "/api/asset/importOCRModels", MultipartBody, ResponseOptions{}, "POST")
var RenameAsset = define[RenameAssetRequest, AssetRenameData]("renameAsset", "/api/asset/renameAsset", JSONBody, ResponseOptions{}, "POST")
var FindAssetReferences = define[FindAssetReferencesRequest, AssetReferencesData]("findAssetReferences", "/api/asset/findAssetReferences", JSONBody, ResponseOptions{DataOnError: true}, "POST")
var RelinkAsset = define[RelinkAssetRequest, AssetReferencesData]("relinkAsset", "/api/asset/relinkAsset", JSONBody, ResponseOptions{DataOnError: true}, "POST")
diff --git a/kernel/apicontract/ocr.go b/kernel/apicontract/ocr.go
new file mode 100644
index 0000000000..5b152e0fc7
--- /dev/null
+++ b/kernel/apicontract/ocr.go
@@ -0,0 +1,38 @@
+package apicontract
+
+import "mime/multipart"
+
+// SettingOCR 的选择仅保存在当前设备;切换提供商或模型不删除、重跑已有识别结果。
+// auto 仅控制内核后台识别,手动识别继续使用 /api/asset/ocr 的既有输入和输出。
+type SettingOCR struct {
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ Auto bool `json:"auto"`
+}
+
+type OCRProviderState struct {
+ ID string `json:"id"`
+ Available bool `json:"available"`
+}
+
+type OCRModel struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ BuiltIn bool `json:"builtIn"`
+}
+
+type OCRConfigData struct {
+ Config SettingOCR `json:"config"`
+ Providers []OCRProviderState `json:"providers"`
+ Models []OCRModel `json:"models"`
+}
+
+// ImportOCRModelsRequest 导入配套的 PP-OCRv6 ONNX 模型和 YAML 配置。
+// 两个模型各不超过 256 MiB,两个配置各不超过 1 MiB;成功后文件存放于 data/ocr/models/<内容摘要>/。
+// 导入不自动切换当前模型,失败不覆盖已有模型。内置 Tiny、Small 不写入工作空间。
+type ImportOCRModelsRequest struct {
+ Detector *multipart.FileHeader `json:"detector"`
+ DetectorConfig *multipart.FileHeader `json:"detectorConfig"`
+ Recognizer *multipart.FileHeader `json:"recognizer"`
+ RecognizerConfig *multipart.FileHeader `json:"recognizerConfig"`
+}
diff --git a/kernel/apicontract/ocr_test.go b/kernel/apicontract/ocr_test.go
new file mode 100644
index 0000000000..a89915269d
--- /dev/null
+++ b/kernel/apicontract/ocr_test.go
@@ -0,0 +1,18 @@
+package apicontract
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestOCRSettingStrictInput(t *testing.T) {
+ for _, body := range []string{`{}`, `{"provider":"paddleocr","model":"tiny","auto":null}`, `{"provider":null,"model":"tiny","auto":true}`, `{"provider":"paddleocr","model":"tiny","auto":1}`} {
+ if _, err := SetOCRConfig.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("accepted invalid OCR settings: %s", body)
+ }
+ }
+ request, err := SetOCRConfig.Decode(strings.NewReader(`{"provider":"paddleocr","model":"small","auto":false}`))
+ if err != nil || request.Provider != "paddleocr" || request.Model != "small" || request.Auto {
+ t.Fatalf("valid settings: %+v %v", request, err)
+ }
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 43f9d97cea..23f742cb8e 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -28117,6 +28117,34 @@
],
"additionalProperties": false
},
+ "ImportOCRModelsRequestInput": {
+ "type": "object",
+ "properties": {
+ "detector": {
+ "type": "string",
+ "format": "binary"
+ },
+ "detectorConfig": {
+ "type": "string",
+ "format": "binary"
+ },
+ "recognizer": {
+ "type": "string",
+ "format": "binary"
+ },
+ "recognizerConfig": {
+ "type": "string",
+ "format": "binary"
+ }
+ },
+ "required": [
+ "detector",
+ "detectorConfig",
+ "recognizer",
+ "recognizerConfig"
+ ],
+ "additionalProperties": false
+ },
"ImportRepoKeyRequestInput": {
"type": "object",
"properties": {
@@ -32829,6 +32857,82 @@
],
"additionalProperties": false
},
+ "OCRConfigData": {
+ "type": "object",
+ "properties": {
+ "config": {
+ "$ref": "#/$defs/SettingOCR"
+ },
+ "models": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/OCRModel"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "providers": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/OCRProviderState"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": [
+ "config",
+ "models",
+ "providers"
+ ],
+ "additionalProperties": false
+ },
+ "OCRModel": {
+ "type": "object",
+ "properties": {
+ "builtIn": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "builtIn",
+ "id",
+ "name"
+ ],
+ "additionalProperties": false
+ },
+ "OCRProviderState": {
+ "type": "object",
+ "properties": {
+ "available": {
+ "type": "boolean"
+ },
+ "id": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "available",
+ "id"
+ ],
+ "additionalProperties": false
+ },
"ObsidianAnalysisRequestInput": {
"type": "object",
"properties": {
@@ -45568,6 +45672,46 @@
},
"additionalProperties": false
},
+ "SettingOCR": {
+ "type": "object",
+ "properties": {
+ "auto": {
+ "type": "boolean"
+ },
+ "model": {
+ "type": "string"
+ },
+ "provider": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "auto",
+ "model",
+ "provider"
+ ],
+ "additionalProperties": false
+ },
+ "SettingOCRInput": {
+ "type": "object",
+ "properties": {
+ "auto": {
+ "type": "boolean"
+ },
+ "model": {
+ "type": "string"
+ },
+ "provider": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "auto",
+ "model",
+ "provider"
+ ],
+ "additionalProperties": false
+ },
"SettingPetalDisabledData": {
"type": "object",
"properties": {
@@ -48360,6 +48504,16 @@
}
]
},
+ "ocr": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/SettingOCR"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"oidc": {
"anyOf": [
{
@@ -48536,6 +48690,7 @@
"logLevel",
"mcpOAuth",
"notebookCrypto",
+ "ocr",
"oidc",
"onboarding",
"publish",
@@ -118991,6 +119146,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/asset/getOCRConfig",
+ "handler": "getOCRConfig",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/EmptyRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/OCRConfigData"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/asset/getUnusedAssets",
@@ -119083,6 +119313,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/asset/importOCRModels",
+ "handler": "importOCRModels",
+ "body": "multipart",
+ "request": {
+ "$ref": "#/$defs/ImportOCRModelsRequestInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/OCRModel"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/asset/insertCover",
@@ -119839,6 +120144,81 @@
]
}
},
+ {
+ "method": "POST",
+ "path": "/api/asset/setOCRConfig",
+ "handler": "setOCRConfig",
+ "body": "json",
+ "request": {
+ "$ref": "#/$defs/SettingOCRInput"
+ },
+ "response": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ 0
+ ]
+ },
+ "data": {
+ "$ref": "#/$defs/SettingOCR"
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "object",
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [
+ -1
+ ]
+ },
+ "data": {
+ "anyOf": [
+ {
+ "type": "object",
+ "properties": {
+ "closeTimeout": {
+ "type": "number"
+ }
+ },
+ "required": [
+ "closeTimeout"
+ ],
+ "additionalProperties": false
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "msg": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "code",
+ "msg",
+ "data"
+ ],
+ "additionalProperties": true
+ }
+ ]
+ }
+ },
{
"method": "POST",
"path": "/api/asset/statAsset",
diff --git a/kernel/apicontract/system_conf.go b/kernel/apicontract/system_conf.go
index 6f438a7395..c7a5c6e5c4 100644
--- a/kernel/apicontract/system_conf.go
+++ b/kernel/apicontract/system_conf.go
@@ -22,6 +22,7 @@ type SystemAppConf struct {
Search *SettingSearch `json:"search" api:"optional,nullable"`
Flashcard *SettingFlashcard `json:"flashcard" api:"optional,nullable"`
AI *SettingAI `json:"ai" api:"optional,nullable"`
+ OCR *SettingOCR `json:"ocr" api:"optional,nullable"`
Secrets *SettingSecrets `json:"secrets" api:"optional,nullable"`
Variables *SettingVariables `json:"variables" api:"optional,nullable"`
Bazaar *SettingBazaar `json:"bazaar" api:"optional,nullable"`
diff --git a/kernel/conf/ocr.go b/kernel/conf/ocr.go
new file mode 100644
index 0000000000..bd4f4bfb32
--- /dev/null
+++ b/kernel/conf/ocr.go
@@ -0,0 +1,16 @@
+package conf
+
+// OCR 配置保存在设备配置中,模型文件和识别结果独立于提供商选择。
+type OCR struct {
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ Auto bool `json:"auto"`
+}
+
+func NewOCR(mobile bool) *OCR {
+ model := "small"
+ if mobile {
+ model = "tiny"
+ }
+ return &OCR{Provider: "tesseract", Model: model, Auto: true}
+}
diff --git a/kernel/conf/ocr_test.go b/kernel/conf/ocr_test.go
new file mode 100644
index 0000000000..b8bee5136f
--- /dev/null
+++ b/kernel/conf/ocr_test.go
@@ -0,0 +1,12 @@
+package conf
+
+import "testing"
+
+func TestOCRDeviceDefaults(t *testing.T) {
+ if desktop := NewOCR(false); desktop.Provider != "tesseract" || desktop.Model != "small" || !desktop.Auto {
+ t.Fatalf("desktop defaults: %+v", desktop)
+ }
+ if mobile := NewOCR(true); mobile.Model != "tiny" || !mobile.Auto {
+ t.Fatalf("mobile defaults: %+v", mobile)
+ }
+}
diff --git a/kernel/model/conf.go b/kernel/model/conf.go
index e88cc3cd47..86cd00b331 100644
--- a/kernel/model/conf.go
+++ b/kernel/model/conf.go
@@ -73,6 +73,7 @@ type AppConf struct {
Search *conf.Search `json:"search"` // 搜索配置
Flashcard *conf.Flashcard `json:"flashcard"` // 闪卡配置
AI *conf.AI `json:"ai"` // 人工智能配置
+ OCR *conf.OCR `json:"ocr"` // 本地图片文字识别
Secrets *conf.Secrets `json:"secrets"` // 全局密钥库
Variables *conf.Variables `json:"variables"` // 全局变量库
Bazaar *conf.Bazaar `json:"bazaar"` // 集市配置
@@ -781,6 +782,9 @@ func InitConf() {
}()
}
+ if nil == Conf.OCR {
+ Conf.OCR = conf.NewOCR(util.IsMobileContainer())
+ }
if nil == Conf.AI {
Conf.AI = conf.NewAI()
} else {
@@ -901,6 +905,7 @@ func InitConf() {
go util.InitPandoc(Conf.Export.PandocBin)
go util.InitTesseract()
+ InitOCR()
}
func normalizeFileTreeDefaultIcon(fileTree *conf.FileTree, confFileExists bool) *conf.FileTree {
diff --git a/kernel/model/ocr.go b/kernel/model/ocr.go
index 9eb6965013..a152beb395 100644
--- a/kernel/model/ocr.go
+++ b/kernel/model/ocr.go
@@ -1,81 +1,267 @@
package model
import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
"path/filepath"
+ "runtime"
"strings"
+ "sync"
"time"
+ "github.com/88250/lute/ast"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/ocr"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
"github.com/siyuan-note/siyuan/kernel/util"
)
-func OCRAssetsJob() {
- util.WaitForTesseractInit()
+var ocrRegistry = ocr.NewRegistry()
+var ocrInit sync.Once
+var nativePaddle = &ocr.PaddleProvider{Config: currentPaddleConfig}
- if !util.TesseractEnabled {
- return
+func InitOCR() {
+ ocrInit.Do(func() {
+ if err := ocrRegistry.Register(ocr.Tesseract, util.TesseractProvider{}); err != nil {
+ panic(err)
+ }
+ if err := ocrRegistry.Register(ocr.PaddleOCR, nativePaddle); err != nil {
+ panic(err)
+ }
+ })
+}
+
+func (config *AppConf) GetOCR() conf.OCR {
+ config.m.RLock()
+ defer config.m.RUnlock()
+ if config.OCR == nil {
+ return *conf.NewOCR(util.IsMobileContainer())
}
+ return *config.OCR
+}
- task.AppendTaskWithTimeout(task.OCRImage, 30*time.Second, autoOCRAssets)
+func (config *AppConf) SetOCR(value conf.OCR) error {
+ if value.Provider != string(ocr.Tesseract) && value.Provider != string(ocr.PaddleOCR) {
+ return errors.New("unknown OCR provider")
+ }
+ if value.Model != "tiny" && value.Model != "small" {
+ if len(value.Model) != 64 || strings.Trim(value.Model, "0123456789abcdef") != "" {
+ return errors.New("invalid OCR model ID")
+ }
+ }
+ if value.Provider == string(ocr.PaddleOCR) {
+ if err := ocr.ValidateModels(ocrModelDirectory(value.Model)); err != nil {
+ return err
+ }
+ }
+ config.m.Lock()
+ changed := config.OCR == nil || config.OCR.Provider != value.Provider || config.OCR.Model != value.Model
+ config.OCR = &value
+ config.m.Unlock()
+ config.Save()
+ if changed {
+ go nativePaddle.Close()
+ }
+ return nil
}
-func autoOCRAssets() {
- if !util.TesseractEnabled {
- return
+func ocrModelDirectory(id string) string {
+ if id == "tiny" || id == "small" {
+ return filepath.Join(util.WorkingDir, "stage", "ocr", "models", id)
}
+ return filepath.Join(util.DataDir, "ocr", "models", id)
+}
- defer logging.Recover()
+func currentPaddleConfig() ocr.PaddleConfig {
+ value := Conf.GetOCR()
+ directory := filepath.Join(util.WorkingDir, "stage", "ocr", "runtime", runtime.GOOS+"-"+runtime.GOARCH)
+ filename := "libonnxruntime.so"
+ if runtime.GOOS == "windows" {
+ filename = "onnxruntime.dll"
+ } else if runtime.GOOS == "darwin" {
+ filename = "libonnxruntime.dylib"
+ }
+ result := ocr.PaddleConfig{Directory: ocrModelDirectory(value.Model), Library: filepath.Join(directory, filename)}
+ if runtime.GOOS == "linux" {
+ result.Worker = filepath.Join(directory, "siyuan-ocr")
+ }
+ if runtime.GOOS == "android" {
+ result.Library = "libonnxruntime.so"
+ }
+ return result
+}
- assetsPath := util.GetDataAssetsAbsPath()
- assets := getUnOCRAssetsAbsPaths()
- if 0 < len(assets) {
- for i, assetAbsPath := range assets {
- text := util.GetOcrJsonText(util.Tesseract(assetAbsPath))
- p := strings.TrimPrefix(assetAbsPath, assetsPath)
- p = "assets" + filepath.ToSlash(p)
- util.SetAssetText(p, text)
- if 7 <= i { // 一次任务中最多处理 7 张图片,防止长时间占用系统资源
- break
- }
+// IsEncryptedOCRAsset 保留笔记本查询参数并忽略链接片段,不依赖资源已下载或笔记本已解锁。
+func IsEncryptedOCRAsset(path string) bool {
+ path = strings.SplitN(path, "#", 2)[0]
+ _, boxID, err := assetPathAndBox(path, "")
+ if err == nil && boxID != "" && IsEncryptedBox(boxID) {
+ return true
+ }
+ absPath, err := GetAssetAbsPathInBox(path, "")
+ return err == nil && IsEncryptedAssetPath(absPath)
+}
+
+// OCRAsset 与自动任务共用内核识别和存储流程,失败时保留已有结果。
+func OCRAsset(ctx context.Context, path string) ([]map[string]string, error) {
+ InitOCR()
+ path = strings.SplitN(path, "#", 2)[0]
+ if IsEncryptedOCRAsset(path) {
+ return nil, errors.New(Conf.Language(380))
+ }
+ absPath, err := GetAssetAbsPathInBox(path, "")
+ if err != nil {
+ return nil, err
+ }
+ if IsEncryptedAssetPath(absPath) {
+ return nil, errors.New(Conf.Language(380))
+ }
+ if err = EnsureAssetLocal(absPath); err != nil {
+ return nil, err
+ }
+ value := Conf.GetOCR()
+ if value.Provider == string(ocr.Tesseract) {
+ if err = util.WaitForTesseractInitContext(ctx); err != nil {
+ return nil, err
}
}
+ rows, err := ocrRegistry.Recognize(ctx, ocr.ProviderID(value.Provider), absPath)
+ if err != nil {
+ return nil, err
+ }
+ canonical, _, err := assetPathAndBox(path, "")
+ if err != nil {
+ return nil, err
+ }
+ SetOCRAssetText(canonical, util.GetOcrJsonText(rows))
+ return rows, nil
+}
- util.CleanNotExistAssetsTexts()
+func SetOCRAssetText(path, text string) {
+ if IsEncryptedOCRAsset(path) {
+ return
+ }
+ path = util.OCRAssetKey(path)
+ util.SetAssetText(path, text)
+ documents, err := sql.QueryOCRAssetDocuments(path)
+ if err != nil {
+ logging.LogErrorf("query OCR asset documents failed: %s", err)
+ return
+ }
+ for _, document := range documents {
+ if IsEncryptedBox(document.Box) {
+ continue
+ }
+ tree, loadErr := LoadTreeByBlockIDInExactBox(document.RootID, document.Box)
+ if loadErr != nil {
+ logging.LogWarnf("load OCR asset document failed: %s", loadErr)
+ continue
+ }
+ ids := map[string]bool{}
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || node.Type != ast.NodeImage {
+ return ast.WalkContinue
+ }
+ destination := node.ChildByType(ast.NodeLinkDest)
+ if destination == nil || util.OCRAssetKey(destination.TokensStr()) != path {
+ return ast.WalkContinue
+ }
+ for parent := node.Parent; parent != nil && parent.Type != ast.NodeDocument; parent = parent.Parent {
+ if parent.IsBlock() && !ids[parent.ID] {
+ ids[parent.ID] = true
+ sql.IndexNodeQueue(parent.ID)
+ }
+ }
+ return ast.WalkSkipChildren
+ })
+ }
+}
- // 刷新 OCR 结果到数据库
- util.NodeOCRQueueLock.Lock()
- defer util.NodeOCRQueueLock.Unlock()
- for _, id := range util.NodeOCRQueue {
- sql.IndexNodeQueue(id)
+func OCRAssetsJob() {
+ value := Conf.GetOCR()
+ if !value.Auto {
+ return
}
- util.NodeOCRQueue = nil
+ if value.Provider == string(ocr.Tesseract) {
+ util.WaitForTesseractInit()
+ }
+ if !ocrRegistry.Available(ocr.ProviderID(value.Provider)) {
+ return
+ }
+ task.AppendTaskWithTimeout(task.OCRImage, 30*time.Second, autoOCRAssets)
}
-func getUnOCRAssetsAbsPaths() (ret []string) {
- // 只获取需要 OCR 的资源
- ocrAssets := cache.FilterAssets(func(path string, asset *cache.Asset) bool {
- return util.IsTesseractExtractable(asset.Path)
- })
+var ocrRetry sync.Map
- assetsPath := util.GetDataAssetsAbsPath()
- for _, asset := range ocrAssets {
- // 跳过已经存在 OCR 文本的资源
+func autoOCRAssets() {
+ defer logging.Recover()
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ value := Conf.GetOCR()
+ if !value.Auto {
+ return
+ }
+ assets := cache.FilterAssets(func(path string, asset *cache.Asset) bool { return util.IsTesseractExtractable(asset.Path) })
+ processed := 0
+ for _, asset := range assets {
+ if ctx.Err() != nil || processed >= 7 {
+ break
+ }
if util.ExistsAssetText(asset.Path) {
continue
}
- absPath := filepath.Join(assetsPath, strings.TrimPrefix(asset.Path, "assets"))
- // 加密笔记本的 asset 是密文,跳过 OCR(避免密文图片产出垃圾文本污染搜索索引)
- if IsEncryptedAssetPath(absPath) {
+ key := fmt.Sprintf("%s:%s:%s", value.Provider, value.Model, asset.Path)
+ if retry, exists := ocrRetry.Load(key); exists && time.Now().Before(retry.(time.Time)) {
continue
}
- ret = append(ret, absPath)
+ absPath, err := GetAssetAbsPathInBox(asset.Path, "")
+ if err != nil || IsEncryptedAssetPath(absPath) {
+ continue
+ }
+ processed++
+ if _, err = OCRAsset(ctx, asset.Path); err != nil {
+ ocrRetry.Store(key, time.Now().Add(10*time.Minute))
+ logging.LogWarnf("automatic OCR failed: %s", err)
+ } else {
+ ocrRetry.Delete(key)
+ }
}
- return
+ if _, err := DeferredSyncAssets(); err != nil {
+ logging.LogWarnf("skip OCR text cleanup: %s", err)
+ } else {
+ util.CleanNotExistAssetsTexts(func(path string) bool {
+ _, err := GetAssetAbsPathInBox(strings.SplitN(path, "#", 2)[0], "")
+ return err == nil
+ })
+ }
+ util.NodeOCRQueueLock.Lock()
+ for _, id := range util.NodeOCRQueue {
+ sql.IndexNodeQueue(id)
+ }
+ util.NodeOCRQueue = nil
+ util.NodeOCRQueueLock.Unlock()
}
-func FlushAssetsTextsJob() {
- util.SaveAssetsTexts()
+func OCRModels() []string {
+ result := []string{"tiny", "small"}
+ entries, _ := os.ReadDir(filepath.Join(util.DataDir, "ocr", "models"))
+ for _, entry := range entries {
+ id := entry.Name()
+ if entry.IsDir() && len(id) == 64 && strings.Trim(id, "0123456789abcdef") == "" && ocr.ValidateModels(ocrModelDirectory(id)) == nil {
+ result = append(result, id)
+ }
+ }
+ return result
+}
+
+func OCRProviderAvailable(id string) bool {
+ InitOCR()
+ return ocrRegistry.Available(ocr.ProviderID(id))
}
+
+func FlushAssetsTextsJob() { util.SaveAssetsTexts() }
diff --git a/kernel/model/ocr_import.go b/kernel/model/ocr_import.go
new file mode 100644
index 0000000000..b224d4f551
--- /dev/null
+++ b/kernel/model/ocr_import.go
@@ -0,0 +1,106 @@
+package model
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "io"
+ "mime/multipart"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/siyuan-note/siyuan/kernel/ocr"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// ImportOCRModels 使用固定目标文件名和内容摘要标识,不信任上传文件名或绝对路径。
+func ImportOCRModels(ctx context.Context, files []*multipart.FileHeader) (string, error) {
+ if len(files) != 4 {
+ return "", errors.New("four OCR model files are required")
+ }
+ root := filepath.Join(util.DataDir, "ocr", "models")
+ for _, directory := range []string{filepath.Dir(root), root} {
+ if err := os.Mkdir(directory, 0755); err != nil && !os.IsExist(err) {
+ return "", err
+ }
+ info, err := os.Lstat(directory)
+ if err != nil {
+ return "", err
+ }
+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
+ return "", errors.New("OCR models must use a workspace directory")
+ }
+ }
+ if err := os.MkdirAll(util.TempDir, 0755); err != nil {
+ return "", err
+ }
+ staging, err := os.MkdirTemp(util.TempDir, "ocr-import-")
+ if err != nil {
+ return "", err
+ }
+ defer os.RemoveAll(staging)
+ digest := sha256.New()
+ for i, path := range []string{"det/inference.onnx", "det/inference.yml", "rec/inference.onnx", "rec/inference.yml"} {
+ limit := int64(256 * 1024 * 1024)
+ if strings.HasSuffix(path, ".yml") {
+ limit = 1024 * 1024
+ }
+ if files[i] == nil || files[i].Size <= 0 || files[i].Size > limit {
+ return "", errors.New("invalid OCR model file size")
+ }
+ source, openErr := files[i].Open()
+ if openErr != nil {
+ return "", openErr
+ }
+ destination := filepath.Join(staging, filepath.FromSlash(path))
+ if err = os.MkdirAll(filepath.Dir(destination), 0755); err != nil {
+ source.Close()
+ return "", err
+ }
+ target, createErr := os.Create(destination)
+ if createErr != nil {
+ source.Close()
+ return "", createErr
+ }
+ digest.Write([]byte(path + "\x00"))
+ count, copyErr := io.Copy(io.MultiWriter(target, digest), io.LimitReader(source, limit+1))
+ source.Close()
+ closeErr := target.Close()
+ if copyErr != nil {
+ return "", copyErr
+ }
+ if closeErr != nil {
+ return "", closeErr
+ }
+ if count != files[i].Size || count > limit {
+ return "", errors.New("invalid OCR model file size")
+ }
+ }
+ if err = ocr.ValidateModels(staging); err != nil {
+ return "", err
+ }
+ runtimeConfig := currentPaddleConfig()
+ runtimeConfig.Directory = staging
+ provider := &ocr.PaddleProvider{Config: func() ocr.PaddleConfig { return runtimeConfig }}
+ defer provider.Close()
+ if err = provider.Validate(ctx); err != nil {
+ return "", err
+ }
+ id := hex.EncodeToString(digest.Sum(nil))
+ destination := filepath.Join(root, id)
+ if info, statErr := os.Lstat(destination); statErr == nil {
+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
+ return "", errors.New("invalid OCR model directory")
+ }
+ return id, ocr.ValidateModels(destination)
+ } else if !os.IsNotExist(statErr) {
+ return "", statErr
+ }
+ if err = os.Rename(staging, destination); err != nil {
+ return "", err
+ }
+ IncSyncIfNeeded(destination)
+ return id, nil
+}
diff --git a/kernel/model/ocr_index_test.go b/kernel/model/ocr_index_test.go
new file mode 100644
index 0000000000..315537a0d9
--- /dev/null
+++ b/kernel/model/ocr_index_test.go
@@ -0,0 +1,198 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/cache"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/ocr"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type ocrFixtureProvider struct {
+ rows []map[string]string
+ err error
+ called bool
+}
+
+func (*ocrFixtureProvider) Available() bool { return true }
+func (p *ocrFixtureProvider) Recognize(context.Context, string) ([]map[string]string, error) {
+ p.called = true
+ return p.rows, p.err
+}
+
+func TestOCRResultReindexesWithoutTesseract(t *testing.T) {
+ const child = "SIYUAN_TEST_OCR_INDEX"
+ if os.Getenv(child) != "1" {
+ command := exec.Command(os.Args[0], "-test.run=^TestOCRResultReindexesWithoutTesseract$", "-test.timeout=45s", "-test.v")
+ command.Env = append(os.Environ(), child+"=1")
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("OCR index subprocess: %v\n%s", err, output)
+ }
+ return
+ }
+ fixture := setupFileOperationTest(t)
+ Conf.Search, Conf.Editor, Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()
+ Conf.OCR = &conf.OCR{Provider: "paddleocr", Model: "tiny", Auto: true}
+ util.WorkspaceDir = filepath.Dir(util.DataDir)
+ util.TempDir, util.HistoryDir = t.TempDir(), t.TempDir()
+ util.ConfDir = t.TempDir()
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ util.TesseractEnabled = false
+ path := "assets/image-20261001000000-abcdefg.png"
+ if err := os.MkdirAll(filepath.Join(util.DataDir, "assets"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(util.DataDir, filepath.FromSlash(path)), []byte("image fixture"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ tree := treenode.NewTree(fixture.box.ID, "/20261001000001-abcdefg.sy", "/OCR", "OCR")
+ paragraph := treenode.NewParagraph("20261001000002-abcdefg")
+ parsed := parse.Parse("ocr", []byte("![fixture]("+path+")"), util.NewLute().ParseOptions)
+ image := parsed.Root.FirstChild.FirstChild
+ image.Unlink()
+ paragraph.AppendChild(image)
+ tree.Root.AppendChild(paragraph)
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ sql.FlushQueue()
+ provider := &ocrFixtureProvider{rows: []map[string]string{{"text": "nativeocrkeyword", "conf": "99"}}}
+ ocrRegistry = ocr.NewRegistry()
+ if err := ocrRegistry.Register(ocr.PaddleOCR, provider); err != nil {
+ t.Fatal(err)
+ }
+ ocrInit.Do(func() {})
+ if _, err := OCRAsset(context.Background(), path+"#fragment"); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ block := sql.GetBlock(paragraph.ID)
+ if block == nil || !strings.Contains(block.Content, "nativeocrkeyword") {
+ t.Fatalf("OCR was not indexed: %+v", block)
+ }
+ matches, err := sql.QueryNoLimit("SELECT id FROM blocks_fts WHERE blocks_fts MATCH 'nativeocrkeyword'")
+ if err != nil || len(matches) == 0 {
+ t.Fatalf("OCR did not reach full-text search: %v, %v", matches, err)
+ }
+ SetOCRAssetText(path+"#fragment", "editedocrkeyword")
+ sql.FlushQueue()
+ stored, queryErr := sql.QueryNoLimitArgs("SELECT content FROM blocks WHERE id = ?", paragraph.ID)
+ if queryErr != nil || len(stored) != 1 || !strings.Contains(stored[0]["content"].(string), "editedocrkeyword") || strings.Contains(stored[0]["content"].(string), "nativeocrkeyword") {
+ t.Fatalf("edited OCR was not indexed: %v, %v", stored, queryErr)
+ }
+ matches, err = sql.QueryNoLimit("SELECT id FROM blocks_fts WHERE blocks_fts MATCH 'nativeocrkeyword'")
+ if err != nil || len(matches) != 0 {
+ t.Fatalf("obsolete OCR remained in full-text search: %v, %v", matches, err)
+ }
+ provider.err = errors.New("inference failed")
+ if _, err := OCRAsset(context.Background(), path); err == nil {
+ t.Fatal("failed provider returned success")
+ }
+ if util.GetAssetText(path) != "editedocrkeyword" {
+ t.Fatal("failed recognition changed saved text")
+ }
+ provider.called = false
+ const notebookPath = "assets/notebook-image.png"
+ notebookImage := filepath.Join(util.DataDir, fixture.box.ID, filepath.FromSlash(notebookPath))
+ if err := os.MkdirAll(filepath.Dir(notebookImage), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(notebookImage, []byte("notebook image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ SetOCRAssetText(notebookPath, "notebook result")
+ cache.LoadAssets()
+ if !cache.ExistAsset(path) {
+ t.Fatal("automatic OCR fixture was not cached")
+ }
+ autoOCRAssets()
+ if provider.called {
+ t.Fatal("automatic OCR reran an existing result")
+ }
+ if util.GetAssetText(notebookPath) != "notebook result" {
+ t.Fatal("automatic cleanup deleted a notebook asset result")
+ }
+ util.RemoveAssetText(path)
+ provider.err = nil
+ Conf.OCR.Auto = false
+ autoOCRAssets()
+ if provider.called {
+ t.Fatal("disabled automatic OCR reached provider")
+ }
+ Conf.OCR.Auto = true
+ autoOCRAssets()
+ if !provider.called || !strings.Contains(util.GetAssetText(path), "nativeocrkeyword") {
+ t.Fatalf("headless automatic OCR did not save text: called=%v text=%q", provider.called, util.GetAssetText(path))
+ }
+ const encryptedBox = "20261001000003-abcdefg"
+ key := bytes.Repeat([]byte{5}, 32)
+ ciphertext, err := EncryptAsset(encryptedBox, "encrypted.png", "encrypted.png", key, []byte("private image"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxConfig := conf.NewBoxConf()
+ boxConfig.Encrypted = true
+ configBytes, _ := json.Marshal(boxConfig)
+ for name, value := range map[string][]byte{".siyuan/conf.json": configBytes, "assets/encrypted.png": ciphertext} {
+ filename := filepath.Join(util.DataDir, encryptedBox, filepath.FromSlash(name))
+ if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filename, value, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := ocrRegistry.Register(ocr.Tesseract, provider); err != nil {
+ t.Fatal(err)
+ }
+ for _, unlocked := range []bool{false, true} {
+ if unlocked {
+ setDEKForTest(encryptedBox, key)
+ repairEncryptedBoxStateFromDEK(encryptedBox)
+ }
+ for _, selected := range []string{"paddleocr", "tesseract"} {
+ Conf.OCR.Provider = selected
+ for _, path := range []string{"assets/encrypted.png?box=" + encryptedBox, "assets/encrypted.png?box=" + encryptedBox + "#fragment", "assets/missing.png?box=" + encryptedBox + "#fragment"} {
+ provider.called = false
+ if _, err := OCRAsset(context.Background(), path); err == nil || provider.called {
+ t.Fatalf("encrypted OCR reached %s (unlocked=%v): %v", selected, unlocked, err)
+ }
+ SetOCRAssetText(path, "private text")
+ if util.ExistsAssetText(path) {
+ t.Fatal("encrypted OCR leaked into global text cache")
+ }
+ }
+ if util.ExistsAssetText("assets/encrypted.png") {
+ t.Fatal("encrypted OCR leaked into global text cache")
+ }
+ }
+ }
+ after, err := os.ReadFile(filepath.Join(util.DataDir, encryptedBox, "assets", "encrypted.png"))
+ if err != nil || !bytes.Equal(after, ciphertext) {
+ t.Fatal("encrypted OCR changed source ciphertext")
+ }
+}
diff --git a/kernel/ocr/ONNXRUNTIME-LICENSE b/kernel/ocr/ONNXRUNTIME-LICENSE
new file mode 100644
index 0000000000..48bc6bb499
--- /dev/null
+++ b/kernel/ocr/ONNXRUNTIME-LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) Microsoft Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/kernel/ocr/boxes.go b/kernel/ocr/boxes.go
new file mode 100644
index 0000000000..f96c83e82b
--- /dev/null
+++ b/kernel/ocr/boxes.go
@@ -0,0 +1,222 @@
+package ocr
+
+import (
+ "errors"
+ "image"
+ "image/color"
+ "math"
+ "sort"
+
+ "github.com/disintegration/imaging"
+)
+
+type point struct{ x, y float64 }
+type textBox [4]point
+
+func (b textBox) bounds() (left, top, right, bottom float64) {
+ left, top, right, bottom = b[0].x, b[0].y, b[0].x, b[0].y
+ for _, p := range b[1:] {
+ left = math.Min(left, p.x)
+ top = math.Min(top, p.y)
+ right = math.Max(right, p.x)
+ bottom = math.Max(bottom, p.y)
+ }
+ return
+}
+
+func detectBoxes(result tensor, width, height int, config modelConfig) ([]textBox, error) {
+ if len(result.shape) != 4 || result.shape[0] != 1 || result.shape[1] != 1 || result.shape[2] <= 0 || result.shape[3] <= 0 || result.shape[2]*result.shape[3] != int64(len(result.data)) {
+ return nil, errors.New("unsupported OCR detector output shape")
+ }
+ w, h := int(result.shape[3]), int(result.shape[2])
+ visited := make([]bool, w*h)
+ var boxes []textBox
+ for start, value := range result.data {
+ if visited[start] || float64(value) <= config.PostProcess.Threshold {
+ continue
+ }
+ visited[start] = true
+ queue := []int{start}
+ var boundary []point
+ score := float64(0)
+ for index := 0; index < len(queue); index++ {
+ at := queue[index]
+ x, y := at%w, at/w
+ score += float64(result.data[at])
+ edge := false
+ for dy := -1; dy <= 1; dy++ {
+ for dx := -1; dx <= 1; dx++ {
+ nx, ny := x+dx, y+dy
+ if nx < 0 || nx >= w || ny < 0 || ny >= h {
+ edge = true
+ continue
+ }
+ next := ny*w + nx
+ if float64(result.data[next]) <= config.PostProcess.Threshold {
+ edge = true
+ continue
+ }
+ if !visited[next] {
+ visited[next] = true
+ queue = append(queue, next)
+ }
+ }
+ }
+ if edge {
+ boundary = append(boundary, point{float64(x), float64(y)})
+ }
+ }
+ if len(boundary) < 4 || score/float64(len(queue)) < config.PostProcess.BoxThreshold {
+ continue
+ }
+ hull := convexHull(boundary)
+ box, bw, bh := minimumBox(hull)
+ if math.Min(bw, bh) < 3 {
+ continue
+ }
+ area, perimeter := float64(0), float64(0)
+ for i, p := range hull {
+ q := hull[(i+1)%len(hull)]
+ area += p.x*q.y - q.x*p.y
+ perimeter += math.Hypot(q.x-p.x, q.y-p.y)
+ }
+ if perimeter <= 0 {
+ continue
+ }
+ distance := math.Abs(area) / 2 * config.PostProcess.Unclip / perimeter
+ u := point{(box[1].x - box[0].x) / bw, (box[1].y - box[0].y) / bw}
+ v := point{(box[3].x - box[0].x) / bh, (box[3].y - box[0].y) / bh}
+ for i := range box {
+ du, dv := -distance, -distance
+ if i == 1 || i == 2 {
+ du = distance
+ }
+ if i >= 2 {
+ dv = distance
+ }
+ box[i].x = (box[i].x + du*u.x + dv*v.x) * float64(width) / float64(w)
+ box[i].y = (box[i].y + du*u.y + dv*v.y) * float64(height) / float64(h)
+ }
+ boxes = append(boxes, box)
+ if len(boxes) >= 3000 {
+ break
+ }
+ }
+ // 先按纵坐标排序,再将同一行按横坐标排列,避免比较器的不传递关系。
+ sort.Slice(boxes, func(i, j int) bool { _, a, _, _ := boxes[i].bounds(); _, b, _, _ := boxes[j].bounds(); return a < b })
+ for start := 0; start < len(boxes); {
+ _, top, _, bottom := boxes[start].bounds()
+ end := start + 1
+ for end < len(boxes) {
+ _, next, _, _ := boxes[end].bounds()
+ if next-top > math.Max(10, (bottom-top)/2) {
+ break
+ }
+ end++
+ }
+ sort.Slice(boxes[start:end], func(i, j int) bool {
+ a, _, _, _ := boxes[start+i].bounds()
+ b, _, _, _ := boxes[start+j].bounds()
+ return a < b
+ })
+ start = end
+ }
+ return boxes, nil
+}
+
+func convexHull(points []point) []point {
+ sort.Slice(points, func(i, j int) bool {
+ if points[i].x == points[j].x {
+ return points[i].y < points[j].y
+ }
+ return points[i].x < points[j].x
+ })
+ cross := func(a, b, c point) float64 { return (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x) }
+ hull := make([]point, 0, len(points)*2)
+ for _, p := range points {
+ for len(hull) >= 2 && cross(hull[len(hull)-2], hull[len(hull)-1], p) <= 0 {
+ hull = hull[:len(hull)-1]
+ }
+ hull = append(hull, p)
+ }
+ lower := len(hull)
+ for i := len(points) - 2; i >= 0; i-- {
+ for len(hull) > lower && cross(hull[len(hull)-2], hull[len(hull)-1], points[i]) <= 0 {
+ hull = hull[:len(hull)-1]
+ }
+ hull = append(hull, points[i])
+ }
+ return hull[:len(hull)-1]
+}
+
+func minimumBox(hull []point) (textBox, float64, float64) {
+ best := math.Inf(1)
+ var result textBox
+ var width, height float64
+ for i, p := range hull {
+ q := hull[(i+1)%len(hull)]
+ angle := math.Atan2(q.y-p.y, q.x-p.x)
+ // 保持第一条边尽量水平,使裁剪后的文字方向稳定。
+ for angle > math.Pi/4 {
+ angle -= math.Pi / 2
+ }
+ for angle < -math.Pi/4 {
+ angle += math.Pi / 2
+ }
+ c, s := math.Cos(angle), math.Sin(angle)
+ left, top, right, bottom := math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)
+ for _, v := range hull {
+ x, y := v.x*c+v.y*s, -v.x*s+v.y*c
+ left = math.Min(left, x)
+ right = math.Max(right, x)
+ top = math.Min(top, y)
+ bottom = math.Max(bottom, y)
+ }
+ area := (right - left) * (bottom - top)
+ if area >= best {
+ continue
+ }
+ best = area
+ width, height = right-left, bottom-top
+ for j, v := range [4]point{{left, top}, {right, top}, {right, bottom}, {left, bottom}} {
+ result[j] = point{v.x*c - v.y*s, v.x*s + v.y*c}
+ }
+ }
+ return result, width, height
+}
+
+func cropBox(img image.Image, box textBox) image.Image {
+ w := min(8192, max(1, int(math.Round(math.Hypot(box[1].x-box[0].x, box[1].y-box[0].y)))))
+ h := min(8192, max(1, int(math.Round(math.Hypot(box[3].x-box[0].x, box[3].y-box[0].y)))))
+ // 先缩放到识别高度,避免为大型倾斜文本框分配额外的原始分辨率图像。
+ scale := math.Min(1, 48/float64(min(w, h)))
+ w, h = max(1, int(float64(w)*scale)), max(1, int(float64(h)*scale))
+ source, ok := img.(*image.NRGBA)
+ if !ok {
+ source = imaging.Clone(img)
+ }
+ result := image.NewNRGBA(image.Rect(0, 0, w, h))
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ u, v := (float64(x)+.5)/float64(w), (float64(y)+.5)/float64(h)
+ sx, sy := box[0].x+u*(box[1].x-box[0].x)+v*(box[3].x-box[0].x), box[0].y+u*(box[1].y-box[0].y)+v*(box[3].y-box[0].y)
+ ix, iy := int(math.Floor(sx)), int(math.Floor(sy))
+ fx, fy := sx-float64(ix), sy-float64(iy)
+ var channels [4]float64
+ for dy := 0; dy < 2; dy++ {
+ for dx := 0; dx < 2; dx++ {
+ weight := ((1-fx)*float64(1-dx) + fx*float64(dx)) * ((1-fy)*float64(1-dy) + fy*float64(dy))
+ pixel := source.NRGBAAt(max(0, min(source.Bounds().Dx()-1, ix+dx)), max(0, min(source.Bounds().Dy()-1, iy+dy)))
+ for c, value := range [4]uint8{pixel.R, pixel.G, pixel.B, pixel.A} {
+ channels[c] += float64(value) * weight
+ }
+ }
+ }
+ result.SetNRGBA(x, y, color.NRGBA{uint8(channels[0]), uint8(channels[1]), uint8(channels[2]), uint8(channels[3])})
+ }
+ }
+ if h >= w*3/2 {
+ return imaging.Rotate90(result)
+ }
+ return result
+}
diff --git a/kernel/ocr/cmd/ocr-worker/main.go b/kernel/ocr/cmd/ocr-worker/main.go
new file mode 100644
index 0000000000..489573c42a
--- /dev/null
+++ b/kernel/ocr/cmd/ocr-worker/main.go
@@ -0,0 +1,40 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "os"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/ocr"
+)
+
+func main() {
+ var request ocr.WorkerRequest
+ err := json.NewDecoder(io.LimitReader(os.Stdin, 16384)).Decode(&request)
+ if err == nil && request.Config.Worker != "" {
+ err = fmt.Errorf("recursive OCR worker is forbidden")
+ }
+ if err == nil {
+ provider := &ocr.PaddleProvider{Config: func() ocr.PaddleConfig { return request.Config }}
+ defer provider.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ var rows []map[string]string
+ if request.Image == "" {
+ err = provider.Validate(ctx)
+ rows = []map[string]string{}
+ } else {
+ rows, err = provider.Recognize(ctx, request.Image)
+ }
+ if err == nil {
+ err = json.NewEncoder(os.Stdout).Encode(rows)
+ }
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
diff --git a/kernel/ocr/onnxruntime_c_api.h b/kernel/ocr/onnxruntime_c_api.h
new file mode 100644
index 0000000000..6ae1539d4c
--- /dev/null
+++ b/kernel/ocr/onnxruntime_c_api.h
@@ -0,0 +1,8289 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+// See docs\c_cxx\README.md on generating the Doxygen documentation from this file
+
+/** \mainpage ONNX Runtime
+ *
+ * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models.
+ *
+ * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models.
+ * - \subpage c_cpp_api "Core C, C++ APIs"
+ * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training"
+ *
+ * \page c_cpp_api Core C, C++ APIs
+ * <h1>C</h1>
+ *
+ * ::OrtApi - Click here to go to the structure with all C API functions.
+ *
+ * <h1>C++</h1>
+ *
+ * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes
+ *
+ * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to
+ * automate memory management through standard C++ RAII principles.
+ *
+ * \addtogroup Global
+ * ONNX Runtime C API
+ * @{
+ */
+
+#pragma once
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+/** \brief The API version defined in this header
+ *
+ * This value is used by some API functions to behave as this version of the header expects.
+ */
+#define ORT_API_VERSION 24
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//! @}
+// SAL2 Definitions
+#ifndef _MSC_VER
+#define _In_
+#define _In_z_
+#define _In_opt_
+#define _In_opt_z_
+#define _Out_
+#define _Out_opt_
+#define _Outptr_
+#define _Outptr_opt_
+#define _Inout_
+#define _Inout_opt_
+#define _Frees_ptr_opt_
+#define _Ret_maybenull_
+#define _Ret_notnull_
+#define _Check_return_
+#define _Outptr_result_maybenull_
+#define _Outptr_result_maybenull_z_
+#define _In_reads_(X)
+#define _In_reads_opt_
+#define _Inout_updates_(X)
+#define _Out_writes_(X)
+#define _Out_writes_opt_(X)
+#define _Inout_updates_all_(X)
+#define _Out_writes_bytes_all_(X)
+#define _Out_writes_all_(X)
+#define _Success_(X)
+#define _Outptr_result_buffer_maybenull_(X)
+#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull))
+#else
+#include <specstrings.h>
+#define ORT_ALL_ARGS_NONNULL
+#endif
+
+#ifdef _WIN32
+// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort.
+// dllexport is not used, we use a .def file.
+#ifdef ORT_DLL_IMPORT
+#define ORT_EXPORT __declspec(dllimport)
+#else
+#define ORT_EXPORT
+#endif
+#define ORT_API_CALL __stdcall
+#define ORT_MUST_USE_RESULT
+#define ORTCHAR_T wchar_t
+#else
+// To make symbols visible on macOS/iOS
+#ifdef __APPLE__
+#define ORT_EXPORT __attribute__((visibility("default")))
+#else
+#define ORT_EXPORT
+#endif
+#define ORT_API_CALL
+#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result))
+#define ORTCHAR_T char
+#endif
+
+/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling.
+/// All other strings are UTF-8 encoded, use char and std::string
+#ifndef ORT_TSTR
+#ifdef _WIN32
+#define ORT_TSTR(X) L##X
+// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO.
+#define ORT_TSTR_ON_MACRO(X) L"" X
+#else
+#define ORT_TSTR(X) X
+#define ORT_TSTR_ON_MACRO(X) X
+#endif
+#endif
+
+// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro.
+// Otherwise, ORT_FILE is equivalent to __FILE__.
+#ifndef ORT_FILE
+#define ORT_FILE_INTERNAL(x) ORT_TSTR(x)
+#define ORT_FILE ORT_FILE_INTERNAL(__FILE__)
+#endif
+
+// Any pointer marked with _In_ or _Out_, cannot be NULL.
+
+// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation
+// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that.
+// for ReleaseXXX(...) functions, they can accept NULL pointer.
+
+#ifdef __cplusplus
+// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept.
+// Such complex condition is needed because compilers set __cplusplus value differently.
+#ifndef __has_feature
+#define __has_feature(x) 0
+#endif
+#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept)))
+#define NO_EXCEPTION noexcept
+#else
+#define NO_EXCEPTION throw()
+#endif
+#else
+#define NO_EXCEPTION
+#endif
+
+// __VA_ARGS__ on Windows and Linux are different
+#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION
+
+#define ORT_API_T(RETURN_TYPE, NAME, ...) \
+ RETURN_TYPE(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION
+
+#define ORT_API_STATUS(NAME, ...) \
+ _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \
+ NO_EXCEPTION ORT_MUST_USE_RESULT
+
+// XXX: Unfortunately, SAL annotations are known to not work with function pointers
+#define ORT_API2_STATUS(NAME, ...) \
+ _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT
+
+// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT
+#define ORT_API_STATUS_IMPL(NAME, ...) \
+ _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION
+
+#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input)
+
+#ifdef __DOXYGEN__
+#undef ORT_API_STATUS
+#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__)
+#undef ORT_API2_STATUS
+#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__)
+#undef ORT_CLASS_RELEASE
+#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input)
+#undef NO_EXCEPTION
+#define NO_EXCEPTION
+#endif
+/** \addtogroup Global
+ * ONNX Runtime C API
+ * @{
+ */
+
+/** Copied from TensorProto::DataType
+ * Currently, Ort doesn't support complex64, complex128
+ */
+typedef enum ONNXTensorElementDataType {
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED,
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL,
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16,
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision
+ // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision
+ // Int4 types were introduced in ONNX 1.16. See https://onnx.ai/onnx/technical/int4.html
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT4, // maps to a pair of packed uint4 values (size == 1 byte)
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT4, // maps to a pair of packed int4 values (size == 1 byte)
+ // Float4 types were introduced in ONNX 1.18. See https://onnx.ai/onnx/technical/float4.html
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT4E2M1, // maps to a pair of packed float4 values (size == 1 byte)
+ // Int2 types were introduced in ONNX 1.20. See https://onnx.ai/onnx/technical/int2.html
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT2, // maps to 4 packed uint2 values (size == 1 byte)
+ ONNX_TENSOR_ELEMENT_DATA_TYPE_INT2, // maps to 4 packed int2 values (size == 1 byte)
+} ONNXTensorElementDataType;
+
+// Synced with onnx TypeProto oneof
+typedef enum ONNXType {
+ ONNX_TYPE_UNKNOWN,
+ ONNX_TYPE_TENSOR,
+ ONNX_TYPE_SEQUENCE,
+ ONNX_TYPE_MAP,
+ ONNX_TYPE_OPAQUE,
+ ONNX_TYPE_SPARSETENSOR,
+ ONNX_TYPE_OPTIONAL
+} ONNXType;
+
+// These types are synced with internal
+// SparseFormatFlags
+typedef enum OrtSparseFormat {
+ ORT_SPARSE_UNDEFINED = 0,
+ ORT_SPARSE_COO = 0x1,
+ ORT_SPARSE_CSRC = 0x2,
+ ORT_SPARSE_BLOCK_SPARSE = 0x4
+} OrtSparseFormat;
+
+// Enum allows to query sparse tensor indices
+enum OrtSparseIndicesFormat {
+ ORT_SPARSE_COO_INDICES,
+ ORT_SPARSE_CSR_INNER_INDICES,
+ ORT_SPARSE_CSR_OUTER_INDICES,
+ ORT_SPARSE_BLOCK_SPARSE_INDICES
+};
+
+/** \brief Logging severity levels
+ *
+ * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show.
+ */
+typedef enum OrtLoggingLevel {
+ ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe).
+ ORT_LOGGING_LEVEL_INFO, ///< Informational messages.
+ ORT_LOGGING_LEVEL_WARNING, ///< Warning messages.
+ ORT_LOGGING_LEVEL_ERROR, ///< Error messages.
+ ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe).
+} OrtLoggingLevel;
+
+typedef enum OrtErrorCode {
+ ORT_OK,
+ ORT_FAIL,
+ ORT_INVALID_ARGUMENT,
+ ORT_NO_SUCHFILE,
+ ORT_NO_MODEL,
+ ORT_ENGINE_ERROR,
+ ORT_RUNTIME_EXCEPTION,
+ ORT_INVALID_PROTOBUF,
+ ORT_MODEL_LOADED,
+ ORT_NOT_IMPLEMENTED,
+ ORT_INVALID_GRAPH,
+ ORT_EP_FAIL,
+ ORT_MODEL_LOAD_CANCELED,
+ ORT_MODEL_REQUIRES_COMPILATION,
+ ORT_NOT_FOUND,
+} OrtErrorCode;
+
+typedef enum OrtOpAttrType {
+ ORT_OP_ATTR_UNDEFINED = 0,
+ ORT_OP_ATTR_INT,
+ ORT_OP_ATTR_INTS,
+ ORT_OP_ATTR_FLOAT,
+ ORT_OP_ATTR_FLOATS,
+ ORT_OP_ATTR_STRING,
+ ORT_OP_ATTR_STRINGS,
+ ORT_OP_ATTR_GRAPH,
+ ORT_OP_ATTR_TENSOR,
+} OrtOpAttrType;
+
+//! @}
+#define ORT_RUNTIME_CLASS(X) \
+ struct Ort##X; \
+ typedef struct Ort##X Ort##X
+
+/** \addtogroup Global
+ * ONNX Runtime C API
+ * @{
+ */
+// The actual types defined have an Ort prefix
+ORT_RUNTIME_CLASS(Env);
+ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success
+ORT_RUNTIME_CLASS(MemoryInfo);
+ORT_RUNTIME_CLASS(IoBinding);
+ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool)
+ORT_RUNTIME_CLASS(Value);
+ORT_RUNTIME_CLASS(RunOptions);
+ORT_RUNTIME_CLASS(TypeInfo);
+ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo);
+ORT_RUNTIME_CLASS(MapTypeInfo);
+ORT_RUNTIME_CLASS(SequenceTypeInfo);
+ORT_RUNTIME_CLASS(OptionalTypeInfo);
+ORT_RUNTIME_CLASS(SessionOptions);
+ORT_RUNTIME_CLASS(CustomOpDomain);
+ORT_RUNTIME_CLASS(ModelMetadata);
+ORT_RUNTIME_CLASS(ThreadPoolParams);
+ORT_RUNTIME_CLASS(ThreadingOptions);
+ORT_RUNTIME_CLASS(ArenaCfg);
+ORT_RUNTIME_CLASS(PrepackedWeightsContainer);
+ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2);
+ORT_RUNTIME_CLASS(NvTensorRtRtxProviderOptions);
+ORT_RUNTIME_CLASS(CUDAProviderOptionsV2);
+ORT_RUNTIME_CLASS(CANNProviderOptions);
+ORT_RUNTIME_CLASS(DnnlProviderOptions);
+ORT_RUNTIME_CLASS(Op);
+ORT_RUNTIME_CLASS(OpAttr);
+ORT_RUNTIME_CLASS(Logger);
+ORT_RUNTIME_CLASS(ShapeInferContext);
+ORT_RUNTIME_CLASS(LoraAdapter);
+ORT_RUNTIME_CLASS(ValueInfo);
+ORT_RUNTIME_CLASS(Node);
+ORT_RUNTIME_CLASS(Graph);
+ORT_RUNTIME_CLASS(Model);
+ORT_RUNTIME_CLASS(ModelCompilationOptions);
+ORT_RUNTIME_CLASS(HardwareDevice);
+ORT_RUNTIME_CLASS(EpDevice);
+ORT_RUNTIME_CLASS(KeyValuePairs);
+ORT_RUNTIME_CLASS(SyncStream); // Opaque class to create an onnxruntime::Stream.
+ORT_RUNTIME_CLASS(ExternalInitializerInfo);
+ORT_RUNTIME_CLASS(ExternalResourceImporter); // Capability object for external resource import
+ORT_RUNTIME_CLASS(ExternalMemoryHandle); // EP-imported view of shared external allocation
+ORT_RUNTIME_CLASS(ExternalSemaphoreHandle); // EP-imported view of shared external semaphore
+ORT_RUNTIME_CLASS(DeviceEpIncompatibilityDetails);
+ORT_RUNTIME_CLASS(EpAssignedSubgraph);
+ORT_RUNTIME_CLASS(EpAssignedNode);
+
+#ifdef _MSC_VER
+typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr;
+#else
+typedef OrtStatus* OrtStatusPtr;
+#endif
+
+/** \brief Memory allocation interface
+ *
+ * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators.
+ *
+ * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed.
+ */
+typedef struct OrtAllocator {
+ uint32_t version; ///< Must be initialized to ORT_API_VERSION
+
+ /// Returns a pointer to an allocated block of `size` bytes
+ void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size);
+
+ /// Free a block of memory previously allocated with OrtAllocator::Alloc
+ void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p);
+
+ /// Return a pointer to an ::OrtMemoryInfo that describes this allocator
+ const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_);
+ /**
+ * @brief Optional allocation function to use for memory allocations made during session initialization.
+ * Use this function if you want to separate allocations made by ORT during Run() calls from
+ * those made during session initialization. This allows for separate memory management strategies for these
+ * allocations.
+ *
+ * \return pointer to an allocated block of `size` bytes. nullptr if size was 0 or allocation failed.
+ *
+ * \since 1.18
+ */
+ void*(ORT_API_CALL* Reserve)(struct OrtAllocator* this_, size_t size);
+
+ /**
+ * @brief Function used to get the statistics of the allocator.
+ *
+ * Return a pointer to the OrtKeyValuePairs structure that contains the statistics of the allocator.
+ * The user should call OrtApi::ReleaseKeyValuePairs when done.
+ *
+ * Current known keys are:
+ * - Limit: Bytes limit of the allocator. -1 if no limit is set.
+ * - InUse: Number of bytes in use.
+ * - TotalAllocated: The total number of allocated bytes by the allocator.
+ * - MaxInUse: The maximum bytes in use.
+ * - NumAllocs: Number of allocations.
+ * - NumReserves: Number of reserves. (Number of calls to Reserve() in arena-based allocators)
+ * - NumArenaExtensions: Number of arena extensions (Relevant only for arena based allocators)
+ * - NumArenaShrinkages: Number of arena shrinkages (Relevant only for arena based allocators)
+ * - MaxAllocSize: The max single allocation seen.
+ *
+ * The allocator is free to add other entries as appropriate.
+ *
+ * \note Implementation of this function is optional and GetStats may be set to a nullptr.
+ * If the OrtAllocator is wrapping an internal ORT allocator that does not implement GetStats
+ * the returned OrtKeyValuePairs instance will be empty.
+ *
+ * \since 1.23
+ */
+ ORT_API2_STATUS(GetStats, _In_ const struct OrtAllocator* this_, _Outptr_ OrtKeyValuePairs** out);
+
+ /** \brief Allocate using a stream.
+ *
+ * If the allocator is stream aware this performs allocation using a stream.
+ *
+ * Alloc will be used if this is nullptr.
+ *
+ * \param[in] this_ OrtAllocator instance
+ * \param[in] size Size of the allocation in bytes. nullptr if size was 0 or allocation failed.
+ * \param[in] stream The stream to allocate on.
+ *
+ * \return pointer to an allocated block of `size` bytes
+ *
+ * \note Implementation of this function is optional and AllocOnStream may be set to a nullptr.
+ * \since 1.23
+ */
+ void*(ORT_API_CALL* AllocOnStream)(struct OrtAllocator* this_, size_t size, OrtSyncStream* stream);
+} OrtAllocator;
+
+typedef void(ORT_API_CALL* OrtLoggingFunction)(
+ void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location,
+ const char* message);
+
+/** \brief Graph optimization level
+ *
+ * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels
+ * for an in-depth understanding of the Graph Optimization Levels.
+ */
+typedef enum GraphOptimizationLevel {
+ ORT_DISABLE_ALL = 0,
+ ORT_ENABLE_BASIC = 1,
+ ORT_ENABLE_EXTENDED = 2,
+ ORT_ENABLE_LAYOUT = 3,
+ ORT_ENABLE_ALL = 99
+} GraphOptimizationLevel;
+
+typedef enum ExecutionMode {
+ ORT_SEQUENTIAL = 0,
+ ORT_PARALLEL = 1,
+} ExecutionMode;
+
+/** \brief Language projection identifiers
+ * /see OrtApi::SetLanguageProjection
+ */
+typedef enum OrtLanguageProjection {
+ ORT_PROJECTION_C = 0,
+ ORT_PROJECTION_CPLUSPLUS = 1,
+ ORT_PROJECTION_CSHARP = 2,
+ ORT_PROJECTION_PYTHON = 3,
+ ORT_PROJECTION_JAVA = 4,
+ ORT_PROJECTION_WINML = 5,
+ ORT_PROJECTION_NODEJS = 6,
+} OrtLanguageProjection;
+
+struct OrtKernelInfo;
+typedef struct OrtKernelInfo OrtKernelInfo;
+struct OrtKernelContext;
+typedef struct OrtKernelContext OrtKernelContext;
+struct OrtCustomOp;
+typedef struct OrtCustomOp OrtCustomOp;
+
+typedef enum OrtAllocatorType {
+ OrtInvalidAllocator = -1,
+ OrtDeviceAllocator = 0,
+ OrtArenaAllocator = 1,
+ OrtReadOnlyAllocator = 2,
+} OrtAllocatorType;
+
+/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider.
+ */
+// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc
+typedef enum OrtMemType {
+ /// Any CPU memory used by non-CPU execution provider
+ OrtMemTypeCPUInput = -2,
+ /// CPU accessible memory outputted by non-CPU execution provider, i.e. HOST_ACCESSIBLE
+ OrtMemTypeCPUOutput = -1,
+ /// CPU accessible memory allocated by non-CPU execution provider, i.e. HOST_ACCESSIBLE
+ OrtMemTypeCPU = OrtMemTypeCPUOutput,
+ /// The default allocator for execution provider
+ OrtMemTypeDefault = 0,
+} OrtMemType;
+
+/** \brief This matches OrtDevice::MemoryType values */
+typedef enum OrtDeviceMemoryType {
+ OrtDeviceMemoryType_DEFAULT = 0, ///< Device memory
+ OrtDeviceMemoryType_HOST_ACCESSIBLE = 5, ///< Shared/pinned memory for transferring between CPU and the device
+} OrtDeviceMemoryType;
+
+/** \brief This mimics OrtDevice type constants so they can be returned in the API
+ */
+typedef enum OrtMemoryInfoDeviceType {
+ OrtMemoryInfoDeviceType_CPU = 0,
+ OrtMemoryInfoDeviceType_GPU = 1,
+ OrtMemoryInfoDeviceType_FPGA = 2,
+ OrtMemoryInfoDeviceType_NPU = 3,
+} OrtMemoryInfoDeviceType;
+
+typedef enum OrtHardwareDeviceType {
+ OrtHardwareDeviceType_CPU,
+ OrtHardwareDeviceType_GPU,
+ OrtHardwareDeviceType_NPU
+} OrtHardwareDeviceType;
+
+/** \brief These are the default EP selection policies used by ORT when doing automatic EP selection.
+ */
+typedef enum OrtExecutionProviderDevicePolicy {
+ OrtExecutionProviderDevicePolicy_DEFAULT,
+ OrtExecutionProviderDevicePolicy_PREFER_CPU,
+ OrtExecutionProviderDevicePolicy_PREFER_NPU,
+ OrtExecutionProviderDevicePolicy_PREFER_GPU,
+ OrtExecutionProviderDevicePolicy_MAX_PERFORMANCE,
+ OrtExecutionProviderDevicePolicy_MAX_EFFICIENCY,
+ OrtExecutionProviderDevicePolicy_MIN_OVERALL_POWER,
+} OrtExecutionProviderDevicePolicy;
+
+/** \brief Reasons why an execution provider might not be compatible with a device
+ */
+typedef enum OrtDeviceEpIncompatibilityReason {
+ OrtDeviceEpIncompatibility_NONE = 0,
+ OrtDeviceEpIncompatibility_DRIVER_INCOMPATIBLE = 1 << 0,
+ OrtDeviceEpIncompatibility_DEVICE_INCOMPATIBLE = 1 << 1,
+ OrtDeviceEpIncompatibility_MISSING_DEPENDENCY = 1 << 2,
+ OrtDeviceEpIncompatibility_UNKNOWN = 1 << 31
+} OrtDeviceEpIncompatibilityReason;
+
+/** \brief Delegate to allow providing custom OrtEpDevice selection logic
+ *
+ * This delegate is called by the EP selection code to allow the user to provide custom device selection logic.
+ * The user can use this to select OrtEpDevice instances from the list of available devices.
+ *
+ * \param ep_devices The list of available devices.
+ * \param num_devices The number of available devices.
+ * \param model_metadata The model metadata.
+ * \param runtime_metadata The runtime metadata. May be nullptr.
+ * \param selected Pre-allocated array to populate with selected OrtEpDevice pointers from ep_devices.
+ * \param max_selected The maximum number of devices that can be selected in the pre-allocated array.
+ Currently the maximum is 8.
+ * \param num_selected The number of selected devices.
+ * \param state Opaque pointer. Required to use the delegate from other languages like C# and python.
+ *
+ * \return OrtStatus* Selection status. Return nullptr on success.
+ * Use CreateStatus to provide error info. Use ORT_FAIL as the error code.
+ * ORT will release the OrtStatus* if not null.
+ */
+typedef OrtStatus*(ORT_API_CALL* EpSelectionDelegate)(_In_ const OrtEpDevice** ep_devices,
+ _In_ size_t num_devices,
+ _In_ const OrtKeyValuePairs* model_metadata,
+ _In_opt_ const OrtKeyValuePairs* runtime_metadata,
+ _Inout_ const OrtEpDevice** selected,
+ _In_ size_t max_selected,
+ _Out_ size_t* num_selected,
+ _In_ void* state);
+
+/** \brief Function called by ORT to write a buffer to a custom destination (e.g., file, stream, etc.).
+ *
+ * \param state Opaque pointer holding the user's state.
+ * \param buffer The buffer to write.
+ * \param buffer_num_bytes The size of the buffer in bytes.
+ *
+ * \return OrtStatus* Write status. Return nullptr on success.
+ * Use CreateStatus to provide error info. Use ORT_FAIL as the error code.
+ * ORT will release the OrtStatus* if not null.
+ */
+typedef OrtStatus*(ORT_API_CALL* OrtWriteBufferFunc)(_In_ void* state,
+ _In_ const void* buffer,
+ _In_ size_t buffer_num_bytes);
+
+/** \brief Function called by ORT to allow user to specify how an initializer should be saved, that is, either
+ * written to an external file or stored within the model. ORT calls this function for every initializer when
+ * generating a model.
+ *
+ * If the function implementation sets the `new_external_info` output parameter to NULL, ORT stores the initializer data
+ * within the generated model.
+ *
+ * Otherwise, if the function implementation sets `new_external_info` to a valid OrtExternalInitializerInfo instance,
+ * ORT assumes that this function stores the initializer data in a file. In this case, ORT configures the model's
+ * initializer to point to the location specified by the `new_external_info` output parameter.
+ *
+ * \param[in] state Opaque pointer holding the user's state.
+ * \param[in] initializer_name The initializer's name as a null-terminated string.
+ * \param[in] initializer_value OrtValue containing the initializer's data, type, and shape.
+ * \param[in] external_info If the initializer is originally stored in an external file, `external_info` contains
+ * the file path, file offset, and the data's byte size within the file. Otherwise,
+ * `external_info` is NULL if the initializer is not originally stored in a file.
+ * \param[out] new_external_info Output parameter set to a new OrtExternalInitializerInfo instance indicating the
+ * location where the function implementation stored the initializer data.
+ * The function implementation must use `OrtApi::CreateExternalInitializerInfo()` to
+ * create the instance.
+ * If the function implementation sets `new_external_info` to NULL,
+ * ORT stores the initializers within the model.
+ *
+ * \note ORT takes ownership of the `new_external_info` output parameter.
+ *
+ * \return OrtStatus* Write status. Return nullptr on success.
+ * Use CreateStatus to provide error info. Use ORT_FAIL as the error code.
+ * ORT will release the OrtStatus* if not null.
+ */
+typedef OrtStatus*(ORT_API_CALL* OrtGetInitializerLocationFunc)(
+ _In_ void* state,
+ _In_ const char* initializer_name,
+ _In_ const OrtValue* initializer_value,
+ _In_opt_ const OrtExternalInitializerInfo* external_info,
+ _Outptr_result_maybenull_ OrtExternalInitializerInfo** new_external_info);
+
+/** \brief Algorithm to use for cuDNN Convolution Op
+ */
+typedef enum OrtCudnnConvAlgoSearch {
+ OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx
+ OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7
+ OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM
+} OrtCudnnConvAlgoSearch;
+
+/** \brief CUDA Provider Options
+ *
+ * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA
+ */
+typedef struct OrtCUDAProviderOptions {
+#ifdef __cplusplus
+ OrtCUDAProviderOptions()
+ : device_id{},
+ cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive},
+ gpu_mem_limit{SIZE_MAX},
+ arena_extend_strategy{},
+ do_copy_in_default_stream{1},
+ has_user_compute_stream{},
+ user_compute_stream{},
+ default_memory_arena_cfg{},
+ tunable_op_enable{false},
+ tunable_op_tuning_enable{false},
+ tunable_op_max_tuning_duration_ms{} {}
+#endif
+
+ /** \brief CUDA device Id
+ * Defaults to 0.
+ */
+ int device_id;
+
+ /** \brief CUDA Convolution algorithm search configuration.
+ * See enum OrtCudnnConvAlgoSearch for more details.
+ * Defaults to OrtCudnnConvAlgoSearchExhaustive.
+ */
+ OrtCudnnConvAlgoSearch cudnn_conv_algo_search;
+
+ /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t)
+ * Defaults to SIZE_MAX.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ size_t gpu_mem_limit;
+
+ /** \brief Strategy used to grow the memory arena
+ * 0 = kNextPowerOfTwo<br>
+ * 1 = kSameAsRequested<br>
+ * Defaults to 0.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ int arena_extend_strategy;
+
+ /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP
+ * 0 = Use separate streams for copying and compute.
+ * 1 = Use the same stream for copying and compute.
+ * Defaults to 1.
+ * WARNING: Setting this to 0 may result in data races for some models.
+ * Please see issue #4829 for more details.
+ */
+ int do_copy_in_default_stream;
+
+ /** \brief Flag indicating if there is a user provided compute stream
+ * Defaults to 0.
+ */
+ int has_user_compute_stream;
+
+ /** \brief User provided compute stream.
+ * If provided, please set `has_user_compute_stream` to 1.
+ */
+ void* user_compute_stream;
+
+ /** \brief CUDA memory arena configuration parameters
+ */
+ OrtArenaCfg* default_memory_arena_cfg;
+
+ /** \brief Enable TunableOp for using.
+ * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default.
+ * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE.
+ */
+ int tunable_op_enable;
+
+ /** \brief Enable TunableOp for tuning.
+ * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default.
+ * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE.
+ */
+ int tunable_op_tuning_enable;
+
+ /** \brief Max tuning duration time limit for each instance of TunableOp.
+ * Defaults to 0 to disable the limit.
+ */
+ int tunable_op_max_tuning_duration_ms;
+
+} OrtCUDAProviderOptions;
+
+/** \brief ROCM Provider Options
+ *
+ * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM
+ */
+typedef struct OrtROCMProviderOptions {
+#ifdef __cplusplus
+ OrtROCMProviderOptions()
+ : device_id{},
+ miopen_conv_exhaustive_search{0},
+ gpu_mem_limit{SIZE_MAX},
+ arena_extend_strategy{},
+ do_copy_in_default_stream{1},
+ has_user_compute_stream{},
+ user_compute_stream{},
+ default_memory_arena_cfg{},
+ enable_hip_graph{false},
+ tunable_op_enable{false},
+ tunable_op_tuning_enable{false},
+ tunable_op_max_tuning_duration_ms{} {}
+#endif
+
+ /** \brief ROCM device Id
+ * Defaults to 0.
+ */
+ int device_id;
+
+ /** \brief ROCM MIOpen Convolution algorithm exhaustive search option.
+ * Defaults to 0 (false).
+ */
+ int miopen_conv_exhaustive_search;
+
+ /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t)
+ * Defaults to SIZE_MAX.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ size_t gpu_mem_limit;
+
+ /** \brief Strategy used to grow the memory arena
+ * 0 = kNextPowerOfTwo<br>
+ * 1 = kSameAsRequested<br>
+ * Defaults to 0.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ int arena_extend_strategy;
+
+ /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP
+ * 0 = Use separate streams for copying and compute.
+ * 1 = Use the same stream for copying and compute.
+ * Defaults to 1.
+ * WARNING: Setting this to 0 may result in data races for some models.
+ * Please see issue #4829 for more details.
+ */
+ int do_copy_in_default_stream;
+
+ /** \brief Flag indicating if there is a user provided compute stream
+ * Defaults to 0.
+ */
+ int has_user_compute_stream;
+
+ /** \brief User provided compute stream.
+ * If provided, please set `has_user_compute_stream` to 1.
+ */
+ void* user_compute_stream;
+
+ /** \brief ROCM memory arena configuration parameters
+ */
+ OrtArenaCfg* default_memory_arena_cfg;
+
+ int enable_hip_graph;
+
+ /** \brief Enable TunableOp for using.
+ * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default.
+ * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE.
+ */
+ int tunable_op_enable;
+
+ /** \brief Enable TunableOp for tuning.
+ * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default.
+ * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE.
+ */
+ int tunable_op_tuning_enable;
+
+ /** \brief Max tuning duration time limit for each instance of TunableOp.
+ * Defaults to 0 to disable the limit.
+ */
+ int tunable_op_max_tuning_duration_ms;
+
+} OrtROCMProviderOptions;
+
+/** \brief TensorRT Provider Options
+ *
+ * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT
+ */
+typedef struct OrtTensorRTProviderOptions {
+ int device_id; ///< CUDA device id (0 = default device)
+ int has_user_compute_stream; // indicator of user specified CUDA compute stream.
+ void* user_compute_stream; // user specified CUDA compute stream.
+ int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability
+ int trt_min_subgraph_size; // minimum size of TensorRT subgraphs
+ size_t trt_max_workspace_size; // maximum workspace size for TensorRT.
+ int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true
+ int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true
+ const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name.
+ int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true
+ int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true
+ int trt_dla_core; // DLA core number. Default 0
+ int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true
+ int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true
+ const char* trt_engine_cache_path; // specify engine cache path
+ int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true
+ const char* trt_engine_decryption_lib_path; // specify engine decryption library path
+ int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true
+ // This is the legacy struct and don't add new fields here.
+ // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h
+ // For non-string field, need to create a new separate api to handle it.
+} OrtTensorRTProviderOptions;
+
+/** \brief MIGraphX Provider Options
+ *
+ * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX
+ */
+typedef struct OrtMIGraphXProviderOptions {
+ int device_id; // hip device id.
+ int migraphx_fp16_enable; // MIGraphX FP16 precision. Default 0 = false, nonzero = true
+ int migraphx_fp8_enable; // MIGraphX FP8 precision. Default 0 = false, nonzero = true
+ int migraphx_int8_enable; // MIGraphX INT8 precision. Default 0 = false, nonzero = true
+ int migraphx_use_native_calibration_table; // MIGraphx INT8 cal table. Default 0 = false, nonzero = true
+ const char* migraphx_int8_calibration_table_name; // MIGraphx INT8 calibration table name
+ int migraphx_save_compiled_model; // migraphx save compiled model. Default 0 = false, nonzero = true
+ const char* migraphx_save_model_path; // migraphx model path name
+ int migraphx_load_compiled_model; // migraphx int8 cal table. Default 0 = false, nonzero = true
+ const char* migraphx_load_model_path; // migraphx model path name
+ bool migraphx_exhaustive_tune; // MIGraphX tuned compile. Default = false, nonzero = true
+
+ /** \brief MIGraphX memory limit (To use all possible memory pass in maximum size_t)
+ * Defaults to SIZE_MAX.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ size_t migraphx_mem_limit;
+
+ /** \brief Strategy used to grow the memory arena
+ * 0 = kNextPowerOfTwo<br>
+ * 1 = kSameAsRequested<br>
+ * Defaults to 0.
+ * \note If a ::OrtArenaCfg has been applied, it will override this field
+ */
+ int migraphx_arena_extend_strategy;
+
+ // This is the legacy struct and don't add new fields here.
+} OrtMIGraphXProviderOptions;
+
+/** \brief OpenVINO Provider Options
+ * \brief This Struct is frozen since ORT 1.13.0. Its maintained part of Legacy API for compatibility.
+ * \brief For latest OpenVINO Provider Options update to the ProviderOptions map.
+ * \brief Latest OpenVINO Provider Options are listed in the
+ * \htmlonly
+ * <a href="https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html#summary-of-options">onnxruntime document.</a>
+ * \endhtmlonly
+ * \see OrtApi::SessionOptionsAppendExecutionProvider()
+ */
+typedef struct OrtOpenVINOProviderOptions {
+#ifdef __cplusplus
+ OrtOpenVINOProviderOptions() : device_type{},
+ enable_npu_fast_compile{},
+ device_id{},
+ num_of_threads{},
+ cache_dir{},
+ context{},
+ enable_opencl_throttling{},
+ enable_dynamic_shapes{} {}
+#endif
+ /** \brief Device type string
+ *
+ * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16"
+ */
+ const char* device_type;
+ unsigned char enable_npu_fast_compile; ///< 0 = disabled, nonzero = enabled
+ const char* device_id;
+ size_t num_of_threads; ///< 0 = Use default number of threads
+ const char* cache_dir; // path is set to empty by default
+ void* context;
+ unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled
+ unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled
+} OrtOpenVINOProviderOptions;
+
+struct OrtApi;
+typedef struct OrtApi OrtApi;
+
+struct OrtTrainingApi;
+typedef struct OrtTrainingApi OrtTrainingApi;
+
+struct OrtModelEditorApi;
+typedef struct OrtModelEditorApi OrtModelEditorApi;
+
+struct OrtCompileApi;
+typedef struct OrtCompileApi OrtCompileApi;
+
+struct OrtInteropApi;
+typedef struct OrtInteropApi OrtInteropApi;
+
+struct OrtEpApi;
+typedef struct OrtEpApi OrtEpApi;
+
+/** \brief The helper interface to get the right version of OrtApi
+ *
+ * Get a pointer to this structure through ::OrtGetApiBase
+ */
+struct OrtApiBase {
+ /** \brief Get a pointer to the requested version of the ::OrtApi
+ *
+ * \param[in] version Must be ::ORT_API_VERSION
+ * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime
+ * older than the version created with this header file.
+ *
+ * One can call GetVersionString() to get the version of the Onnxruntime library for logging
+ * and error reporting purposes.
+ */
+ const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION;
+
+ /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1")
+ *
+ * \return UTF-8 encoded version string. Do not deallocate the returned buffer.
+ */
+ const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION;
+};
+
+typedef struct OrtApiBase OrtApiBase;
+
+/** \brief The Onnxruntime library's entry point to access the C API
+ *
+ * Call this to get the a pointer to an ::OrtApiBase
+ */
+ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION;
+
+/** \brief Thread work loop function
+ *
+ * Onnxruntime will provide the working loop on custom thread creation
+ * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn
+ */
+typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param);
+
+typedef const struct OrtCustomHandleType {
+ char __place_holder;
+}* OrtCustomThreadHandle;
+
+/** \brief Ort custom thread creation function
+ *
+ * The function should return a thread handle to be used in onnxruntime thread pools
+ * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread
+ */
+typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param);
+
+/** \brief Custom thread join function
+ *
+ * Onnxruntime thread pool destructor will call the function to join a custom thread.
+ * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn
+ */
+typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle);
+
+typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api);
+
+/** \brief Callback function for RunAsync
+ *
+ * \param[in] user_data User specific data that passed back to the callback
+ * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr
+ * \param[out] num_outputs Number of outputs, on error, the value will be zero
+ * \param[out] status On error, status will provide details
+ */
+typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status);
+
+/** \brief External memory handle type for importing GPU resources.
+ *
+ * \todo Add OPAQUE_WIN32 for Windows Vulkan-specific memory handles
+ * \todo Add POSIX file descriptor (OPAQUE_FD) for Linux Vulkan/CUDA/OpenCL interop
+ * \todo Add Linux DMA-BUF file descriptor for embedded GPU memory sharing
+ *
+ * \since Version 1.24.
+ */
+typedef enum OrtExternalMemoryHandleType {
+ ORT_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE = 0, /**< Shared HANDLE from ID3D12Device::CreateSharedHandle(resource) */
+ ORT_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP = 1, /**< Shared HANDLE from ID3D12Device::CreateSharedHandle(heap) */
+} OrtExternalMemoryHandleType;
+
+/** \brief Descriptor for importing external memory.
+ *
+ * \note The version field must be set to ORT_API_VERSION.
+ * This ensures forward compatibility as fields may be added in future versions.
+ *
+ * \since Version 1.24.
+ */
+typedef struct OrtExternalMemoryDescriptor {
+ uint32_t version; /**< Must be ORT_API_VERSION */
+ OrtExternalMemoryHandleType handle_type; /**< Type of the external memory handle */
+ void* native_handle; /**< Platform-specific handle (e.g., Windows HANDLE) */
+ size_t size_bytes; /**< Total size in bytes of the external allocation */
+ size_t offset_bytes; /**< Offset in bytes into the allocation (default 0).
+ Base offset for the imported memory region. */
+} OrtExternalMemoryDescriptor;
+
+/** \brief External semaphore type for GPU synchronization.
+ *
+ * \since Version 1.24.
+ */
+typedef enum OrtExternalSemaphoreType {
+ ORT_EXTERNAL_SEMAPHORE_D3D12_FENCE = 0, /**< Shared HANDLE from ID3D12Device::CreateSharedHandle(fence) */
+} OrtExternalSemaphoreType;
+
+/** \brief Descriptor for importing external semaphores.
+ *
+ * \note The version field must be set to ORT_API_VERSION.
+ * This ensures forward compatibility as fields may be added in future versions.
+ *
+ * \since Version 1.24.
+ */
+typedef struct OrtExternalSemaphoreDescriptor {
+ uint32_t version; /**< Must be ORT_API_VERSION */
+ OrtExternalSemaphoreType type; /**< Type of the external semaphore */
+ void* native_handle; /**< Platform-specific handle (e.g., Windows HANDLE) */
+} OrtExternalSemaphoreDescriptor;
+
+/** \brief Descriptor for creating a tensor from imported external memory.
+ *
+ * \note The version field must be set to ORT_API_VERSION.
+ * This ensures forward compatibility as fields may be added in future versions.
+ *
+ * \since Version 1.24.
+ */
+typedef struct OrtExternalTensorDescriptor {
+ uint32_t version; /**< Must be ORT_API_VERSION */
+ ONNXTensorElementDataType element_type; /**< Data type of tensor elements */
+ const int64_t* shape; /**< Array of dimension sizes */
+ size_t rank; /**< Number of dimensions */
+ size_t offset_bytes; /**< Additional offset within imported memory (default 0).
+ Applied relative to OrtExternalMemoryDescriptor::offset_bytes.
+ Enables multiple tensors from the same imported memory handle. */
+} OrtExternalTensorDescriptor;
+
+/*
+ * Public enum for compiled model compatibility across EPs.
+ */
+typedef enum OrtCompiledModelCompatibility {
+ OrtCompiledModelCompatibility_EP_NOT_APPLICABLE = 0,
+ OrtCompiledModelCompatibility_EP_SUPPORTED_OPTIMAL,
+ OrtCompiledModelCompatibility_EP_SUPPORTED_PREFER_RECOMPILATION,
+ OrtCompiledModelCompatibility_EP_UNSUPPORTED,
+} OrtCompiledModelCompatibility;
+
+/** \brief Configuration options for creating an OrtEnv.
+ *
+ * \note The version field must be set to ORT_API_VERSION.
+ * This ensures forward compatibility as fields may be added in future versions.
+ *
+ * \since Version 1.24.
+ */
+typedef struct OrtEnvCreationOptions {
+ uint32_t version; ///< Must be set to ORT_API_VERSION
+
+ /** \brief The logging severity level for the environment. Must be set to a value from OrtLoggingLevel.
+ *
+ * \note Logging messages which are less severe than the `logging_severity_level` are not emitted.
+ *
+ * \note Serves as the default logging severity level for session creation and runs.
+ * Use OrtApi::SetSessionLogSeverityLevel to set a logging severity level for the creation of specific session.
+ * Use OrtApi::RunOptionsSetRunLogSeverityLevel to set a logging severity level for a specific session run.
+ *
+ * \since Version 1.24.
+ */
+ int32_t logging_severity_level;
+
+ /** \brief The log identifier. Must be set to a valid UTF-8 null-terminated string.
+ *
+ * \note This string identifier is copied by ORT.
+ *
+ * \since Version 1.24.
+ */
+ const char* log_id;
+
+ /** \brief Optional custom logging function. May be set to NULL.
+ *
+ * \note The OrtEnvCreationOptions::custom_logging_param is provided as the first argument to this logging function.
+ * This allows passing custom state into the logging function.
+ *
+ * \note This function is only called when a message's severity meets or exceeds the set logging severity level.
+ *
+ * \since Version 1.24.
+ */
+ OrtLoggingFunction custom_logging_function;
+
+ /** \brief Optional state to pass as the first argument to OrtEnvCreationOptions::custom_logger_function.
+ * May be set to NULL.
+ *
+ * \since Version 1.24.
+ */
+ void* custom_logging_param;
+
+ /** \brief Optional threading options for creating an environment with global thread pools shared across sessions.
+ * May be set to NULL.
+ *
+ * \note The OrtThreadingOptions instance is copied by ORT.
+ *
+ * \note Use OrtApi::CreateThreadingOptions() to create an instance of OrtThreadingOptions.
+ *
+ * \note Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use its own
+ * thread pools.
+ *
+ * \since Version 1.24.
+ */
+ const OrtThreadingOptions* threading_options;
+
+ /** \brief Optional environment configuration entries represented as string key-value pairs. May be set to NULL.
+ *
+ * \note The OrtKeyValuePairs instance is copied by ORT.
+ *
+ * \note Refer to onnxruntime_env_config_keys.h for common config entry keys and their supported values.
+ *
+ * \note An application provides environment-level configuration options for execution provider libraries by
+ * using keys with the prefix 'ep_factory.\\<ep_name\\>.'. Ex: the key 'ep_factory.my_ep.some_ep_key' represents
+ * a key named 'some_ep_key' that is meant to be consumed by an execution provider named 'my_ep'. Refer to
+ * the specific execution provider's documentation for valid keys and values.
+ *
+ * \note An application may separately set session-level configuration options for execution providers via other APIs
+ * such as SessionOptionsAppendExecutionProvider_V2, which store configuration entries within OrtSessionOptions.
+ * If an environment-level configuration conflicts with a session-level configuration, then
+ * precedence is determined by the execution provider library itself.
+ *
+ * \since Version 1.24.
+ */
+ const OrtKeyValuePairs* config_entries;
+
+ //
+ // End of fields available in ORT 1.24
+ //
+
+} OrtEnvCreationOptions;
+
+/** \brief The C API
+ *
+ * All C API functions are defined inside this structure as pointers to functions.
+ * Call OrtApiBase::GetApi to get a pointer to it
+ *
+ * \nosubgrouping
+ */
+struct OrtApi {
+ /// \name OrtStatus
+ /// @{
+
+ /**
+ * \brief Create an OrtStatus from a null terminated string
+ *
+ * \param[in] code
+ * \param[in] msg A null-terminated string. Its contents will be copied.
+ * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus
+ */
+ OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
+
+ /** \brief Get OrtErrorCode from OrtStatus
+ *
+ * \param[in] status
+ * \return OrtErrorCode that \p status was created with
+ */
+ OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
+
+ /** \brief Get error string from OrtStatus
+ *
+ * \param[in] status
+ * \return The error message inside the `status`. Do not free the returned value.
+ */
+ const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
+
+ /// @}
+ /// \name OrtEnv
+ /// @{
+
+ /** \brief Create an OrtEnv
+ *
+ * \note Invoking this function will return the same instance of the environment as that returned by a previous call
+ * to another env creation function; all arguments to this function will be ignored.
+ * \param[in] log_severity_level The log severity level.
+ * \param[in] logid The log identifier.
+ * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out);
+
+ /** \brief Create an OrtEnv
+ *
+ * \note Invoking this function will return the same instance of the environment as that returned by a previous call
+ * to another env creation function; all arguments to this function will be ignored. If you want to provide your
+ * own logging function, consider setting it using the SetUserLoggingFunction API instead.
+ * \param[in] logging_function A pointer to a logging function.
+ * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to
+ * `logging_function`. This parameter is optional.
+ * \param[in] log_severity_level The log severity level.
+ * \param[in] logid The log identifier.
+ * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateEnvWithCustomLogger, _In_ OrtLoggingFunction logging_function, _In_opt_ void* logger_param,
+ _In_ OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out);
+
+ /** \brief Enable Telemetry
+ *
+ * \note Telemetry events are on by default since they are lightweight
+ * \param[in] env
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env);
+ /** \brief Disable Telemetry
+ *
+ * \see OrtApi::EnableTelemetryEvents
+ * \param[in] env
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief Create an OrtSession from a model file
+ *
+ * \param[in] env
+ * \param[in] model_path
+ * \param[in] options
+ * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ // TODO: document the path separator convention? '/' vs '\'
+ // TODO: should specify the access characteristics of model_path. Is this read only during the
+ // execution of CreateSession, or does the OrtSession retain a handle to the file/directory
+ // and continue to access throughout the OrtSession lifetime?
+ // What sort of access is needed to model_path : read or read/write?
+ ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path,
+ _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out);
+
+ /** \brief Create an OrtSession from memory
+ *
+ * \param[in] env
+ * \param[in] model_data
+ * \param[in] model_data_length
+ * \param[in] options
+ * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env,
+ _In_ const void* model_data, size_t model_data_length,
+ _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out);
+
+ /** \brief Run the model in an ::OrtSession
+ *
+ * Will not return until the model run has completed. Multiple threads might be used to run the model based on
+ * the options in the ::OrtSession and settings used when creating the ::OrtEnv
+ *
+ * \param[in] session
+ * \param[in] run_options If nullptr, will use a default ::OrtRunOptions
+ * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names
+ * \param[in] inputs Array of ::OrtValue%s of the input values
+ * \param[in] input_len Number of elements in the input_names and inputs arrays
+ * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names
+ * \param[in] output_names_len Number of elements in the output_names and outputs array
+ * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be
+ * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers
+ * to them will be set into the `outputs` array.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options,
+ _In_reads_(input_len) const char* const* input_names,
+ _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len,
+ _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len,
+ _Inout_updates_all_(output_names_len) OrtValue** outputs);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Create an ::OrtSessionOptions object
+ *
+ * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these
+ * functions to enable them in the session:<br>
+ * OrtSessionOptionsAppendExecutionProvider_CPU<br>
+ * OrtSessionOptionsAppendExecutionProvider_CUDA<br>
+ * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)<br>
+ * The order they are called indicates the preference order as well. In other words call this method
+ * on your most preferred execution provider first followed by the less preferred ones.
+ * If none are called Ort will use its internal CPU execution provider.
+ *
+ * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options);
+
+ /** \brief Set filepath to save optimized model after graph level transformations
+ *
+ * \param[in] options
+ * \param[in] optimized_model_filepath
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options,
+ _In_ const ORTCHAR_T* optimized_model_filepath);
+
+ /** \brief Create a copy of an existing ::OrtSessionOptions
+ *
+ * \param[in] in_options OrtSessionOptions to copy
+ * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options,
+ _Outptr_ OrtSessionOptions** out_options);
+
+ /** \brief Set execution mode
+ *
+ * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model
+ * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance.
+ * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details.
+ *
+ * \param[in] options
+ * \param[in] execution_mode
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode);
+
+ /** \brief Enable profiling for a session
+ *
+ * \param[in] options
+ * \param[in] profile_file_prefix
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix);
+
+ /** \brief Disable profiling for a session
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options);
+
+ /** \brief Enable the memory pattern optimization
+ *
+ * The idea is if the input shapes are the same, we could trace the internal memory allocation
+ * and generate a memory pattern for future request. So next time we could just do one allocation
+ * with a big chunk for all the internal memory allocation.
+ * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode)
+ *
+ * \see OrtApi::DisableMemPattern
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options);
+
+ /** \brief Disable the memory pattern optimization
+ *
+ * \see OrtApi::EnableMemPattern
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options);
+
+ /** \brief Enable the memory arena on CPU
+ *
+ * Arena may pre-allocate memory for future usage.
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options);
+
+ /** \brief Disable the memory arena on CPU
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options);
+
+ /** \brief Set session log id
+ *
+ * \param[in] options
+ * \param[in] logid The log identifier.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid);
+
+ /** \brief Set session log verbosity level
+ *
+ * Applies to session load, initialization, etc
+ *
+ * \param[in] options
+ * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level);
+
+ /** \brief Set session log severity level
+ *
+ * \param[in] options
+ * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level);
+
+ /** \brief Set the optimization level to apply when loading a graph
+ *
+ * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation
+ * \param[in,out] options The session options object
+ * \param[in] graph_optimization_level The optimization level
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options,
+ GraphOptimizationLevel graph_optimization_level);
+
+ /** \brief Sets the number of threads used to parallelize the execution within nodes
+ *
+ * When running a single node operation, ex. add, this sets the maximum number of threads to use.
+ *
+ * \note If built with OpenMP, this has no effect on the number of threads used. In this case
+ * use the OpenMP env variables to configure the number of intra op num threads.
+ *
+ * \param[in] options
+ * \param[in] intra_op_num_threads Number of threads to use<br>
+ * A value of 0 will use the default number of threads<br>
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads);
+
+ /** \brief Sets the number of threads used to parallelize the execution of the graph
+ *
+ * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel.
+ *
+ * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1.
+ *
+ * \param[in] options
+ * \param[in] inter_op_num_threads Number of threads to use<br>
+ * A value of 0 will use the default number of threads<br>
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads);
+
+ /// @}
+ /// \name OrtCustomOpDomain
+ /// @{
+
+ /** \brief Create a custom op domain
+ *
+ * \param[in] domain
+ * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out);
+
+ /** \brief Add a custom op to a custom op domain
+ *
+ * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released
+ *
+ * \param[in] custom_op_domain
+ * \param[in] op
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Add custom op domain to a session options
+ *
+ * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released
+ *
+ * \param[in] options
+ * \param[in] custom_op_domain
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain);
+
+ /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2.
+ *
+ * Registers custom ops from a shared library.
+ *
+ * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point:
+ * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api);
+ * It then passes in the provided session options to this function along with the api base.
+ * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in
+ * session options are destroyed, or if an error occurs and it is non null.
+ *
+ * \param[in] options
+ * \param[in] library_path
+ * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief Get input count for a session
+ *
+ * This number must also match the number of inputs passed to OrtApi::Run
+ *
+ * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session
+ *
+ * \param[in] session
+ * \param[out] out Number of inputs
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out);
+
+ /** \brief Get output count for a session
+ *
+ * This number must also match the number of outputs returned by OrtApi::Run
+ *
+ * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session
+ *
+ * \param[in] session
+ * \param[out] out Number of outputs
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out);
+
+ /** \brief Get overridable initializer count
+ *
+ * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName
+ *
+ * \param[in] session
+ * \param[in] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out);
+
+ /** \brief Get input type information
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive)
+ * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Get output type information
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive)
+ * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Get overridable initializer type information
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive)
+ * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Get input name
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive)
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /** \brief Get output name
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive)
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /** \brief Get overridable initializer name
+ *
+ * \param[in] session
+ * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive)
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /// @}
+ /// \name OrtRunOptions
+ /// @{
+
+ /** \brief Create an OrtRunOptions
+ *
+ * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out);
+
+ /** \brief Set per-run log verbosity level
+ *
+ * \see OrtApi::RunOptionsGetRunLogVerbosityLevel
+ *
+ * \param[in] options
+ * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level);
+
+ /** \brief Set per-run log severity level
+ *
+ * \see OrtApi::RunOptionsGetRunLogSeverityLevel
+ *
+ * \param[in] options
+ * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values).
+ */
+ ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level);
+
+ /** \brief Set per-run tag
+ *
+ * This is used in a per-run log identifier.
+ *
+ * \see OrtApi::RunOptionsGetRunTag
+ *
+ * \param[in] options
+ * \param[in] run_tag The run tag.
+ */
+ ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag);
+
+ /** \brief Get per-run log verbosity level
+ *
+ * \see OrtApi::RunOptionsSetRunLogVerbosityLevel
+ *
+ * \param[in] options
+ * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options,
+ _Out_ int* log_verbosity_level);
+
+ /** \brief Get per-run log severity level
+ *
+ * \see OrtApi::RunOptionsSetRunLogSeverityLevel
+ *
+ * \param[in] options
+ * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values).
+ */
+ ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level);
+
+ /** \brief Get per-run tag
+ *
+ * This is used in a per-run log identifier.
+ *
+ * \see OrtApi::RunOptionsSetRunTag
+ *
+ * \param[in] options
+ * \param[out] run_tag The run tag.
+ * Do not free this value, it is owned by `options`. It will be invalidated if the run tag
+ * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed.
+ */
+ ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag);
+
+ /** \brief Set terminate flag
+ *
+ * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error.
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options);
+
+ /** \brief Clears the terminate flag
+ *
+ * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options);
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /** \brief Create a tensor
+ *
+ * Create a tensor using a supplied ::OrtAllocator
+ *
+ * \param[in] allocator
+ * \param[in] shape Pointer to the tensor shape dimensions.
+ * \param[in] shape_len The number of tensor shape dimensions.
+ * \param[in] type
+ * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len,
+ ONNXTensorElementDataType type, _Outptr_ OrtValue** out);
+
+ /** \brief Create a tensor backed by a user supplied buffer
+ *
+ * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after.
+ * p_data is owned by caller. ReleaseValue won't release p_data.
+ *
+ * If you wish to transfer ownership of p_data to ORT use CreateTensorWithDataAndDeleterAsOrtValue.
+ *
+ * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc).
+ * \param[in] p_data Pointer to the data buffer.
+ * \param[in] p_data_len The number of bytes in the data buffer.
+ * \param[in] shape Pointer to the tensor shape dimensions.
+ * \param[in] shape_len The number of tensor shape dimensions.
+ * \param[in] type The data type.
+ * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data,
+ size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type,
+ _Outptr_ OrtValue** out);
+
+ /** \brief Return if an ::OrtValue is a tensor type
+ *
+ * \param[in] value A tensor type (string tensors are not supported)
+ * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out);
+
+ /** \brief Get a pointer to the raw data inside a tensor
+ *
+ * Used to read/write/modify the internal tensor data directly.
+ * \note The returned pointer is valid until the \p value is destroyed.
+ *
+ * \param[in] value A tensor type (string tensors are not supported)
+ * \param[out] out Filled in with a pointer to the internal storage
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out);
+
+ /** \brief Set all strings at once in a string tensor
+ *
+ * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING
+ * \param[in] s An array of strings. Each string in this array must be null terminated.
+ * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len);
+
+ /** \brief Get total byte length for all strings in a string tensor
+ *
+ * Typically used with OrtApi::GetStringTensorContent
+ *
+ * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING
+ * \param[out] len Total byte length of all strings (does not include trailing nulls)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len);
+
+ /** \brief Get all strings from a string tensor
+ *
+ * An example of the results:<br>
+ * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }<br>
+ * \p s must have a size of 11 bytes<br>
+ * \p offsets must have 4 elements<br>
+ * After the call, these values will be filled in:<br>
+ * \p s will contain "Thisisatest"<br>
+ * \p offsets will contain { 0, 4, 6, 7 }<br>
+ * The length of the last string is just s_len - offsets[last]
+ *
+ * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING
+ * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated.
+ * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength)
+ * \param[out] offsets Array of start offsets into the strings written to \p s
+ * \param[in] offsets_len Number of elements in offsets
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s,
+ size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len);
+
+ /// @}
+ /// \name OrtTypeInfo
+ /// @{
+
+ /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo
+ *
+ * \param[in] type_info
+ * \param[out] out Do not free this value, it will be valid until type_info is freed.
+ * If type_info does not represent tensor, this value will be set to nullptr.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info,
+ _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out);
+
+ /** \brief Get ::ONNXType from ::OrtTypeInfo
+ *
+ * \param[in] type_info
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out);
+
+ /// @}
+ /// \name OrtTensorTypeAndShapeInfo
+ /// @{
+
+ /** \brief Create an ::OrtTensorTypeAndShapeInfo object
+ *
+ * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out);
+
+ /** \brief Set element type in ::OrtTensorTypeAndShapeInfo
+ *
+ * \param[in] info
+ * \param[in] type
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type);
+
+ /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo
+ *
+ * \param[in] info
+ * \param[in] dim_values Array with `dim_count` elements. Can contain negative values.
+ * \param[in] dim_count Number of elements in `dim_values`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count);
+
+ /** \brief Get element type in ::OrtTensorTypeAndShapeInfo
+ *
+ * \see OrtApi::SetTensorElementType
+ *
+ * \param[in] info
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info,
+ _Out_ enum ONNXTensorElementDataType* out);
+
+ /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo
+ *
+ * \see OrtApi::GetDimensions
+ *
+ * \param[in] info
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out);
+
+ /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo
+ *
+ * \param[in] info
+ * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo
+ * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values,
+ size_t dim_values_length);
+
+ /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo
+ *
+ * \param[in] info
+ * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names
+ * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info,
+ _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length);
+
+ /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo
+ *
+ * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other).
+ * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1.
+ *
+ * Examples:<br>
+ * [] = 1<br>
+ * [1,3,4] = 12<br>
+ * [2,0,4] = 0<br>
+ * [-1,3,4] = -1<br>
+ *
+ * \param[in] info
+ * \param[out] out Number of elements
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out);
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /** \brief Get type and shape information from a tensor ::OrtValue
+ *
+ * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure
+ * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out);
+
+ /** \brief Get type information of an OrtValue
+ *
+ * \param[in] value
+ * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out);
+
+ /** \brief Get ONNXType of an ::OrtValue
+ *
+ * \param[in] value
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out);
+
+ /// @}
+ /// \name OrtMemoryInfo
+ /// @{
+
+ /** \brief Create an ::OrtMemoryInfo
+ *
+ * \param[in] name
+ * \param[in] type
+ * \param[in] id
+ * \param[in] mem_type
+ * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id,
+ enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out);
+
+ /** \brief Create an ::OrtMemoryInfo for CPU memory
+ *
+ * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0.
+ *
+ * \param[in] type
+ * \param[in] mem_type
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type,
+ _Outptr_ OrtMemoryInfo** out);
+
+ /** \brief Compare ::OrtMemoryInfo objects for equality
+ *
+ * Compares all settings of each ::OrtMemoryInfo for equality
+ *
+ * \param[in] info1
+ * \param[in] info2
+ * \param[out] out Set to 0 if equal, -1 if not equal
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out);
+
+ /** \brief Get name from ::OrtMemoryInfo
+ *
+ * \param[in] ptr
+ * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out);
+
+ /** \brief Get the device id from ::OrtMemoryInfo
+ */
+ ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out);
+
+ /** \brief Get the ::OrtMemType from ::OrtMemoryInfo
+ */
+ ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out);
+
+ /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo
+ */
+ ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out);
+
+ /// @}
+ /// \name OrtAllocator
+ /// @{
+
+ /// \brief Calls OrtAllocator::Alloc function
+ ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out);
+ /// \brief Calls OrtAllocator::Free function
+ ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p);
+ /// \brief Calls OrtAllocator::Info function
+ ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out);
+
+ /** \brief Get the default allocator
+ *
+ * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator.
+ *
+ * \param[out] out Returned value should NOT be freed
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Override session symbolic dimensions
+ *
+ * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable
+ * optimizations that can take advantage of fixed values (such as memory planning, etc)
+ *
+ * \param[in] options
+ * \param[in] dim_denotation
+ * \param[in] dim_value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation,
+ _In_ int64_t dim_value);
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /* Internal information (not seen in Doxygen)
+ *
+ * APIs to support non-tensor types - map and sequence.
+ * Currently only the following types are supported
+ * Note: the following types should be kept in sync with data_types.h
+ * Map types
+ * =========
+ * std::map<std::string, std::string>
+ * std::map<std::string, int64_t>
+ * std::map<std::string, float>
+ * std::map<std::string, double>
+ * std::map<int64_t, std::string>
+ * std::map<int64_t, int64_t>
+ * std::map<int64_t, float>
+ * std::map<int64_t, double>
+ *
+ * Sequence types
+ * ==============
+ * std::vector<std::string>
+ * std::vector<int64_t>
+ * std::vector<float>
+ * std::vector<double>
+ * std::vector<std::map<std::string, float>>
+ * std::vector<std::map<int64_t, float>
+ */
+
+ /** \brief Get non tensor data from an ::OrtValue
+ *
+ * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values
+ * separately. Use index=0 to retrieve keys and index=1 to retrieve values.
+ * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element
+ * of the sequence.
+ *
+ * \param[in] value
+ * \param[in] index See above for usage based on `value` type
+ * \param[in] allocator Allocator used to allocate ::OrtValue
+ * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator,
+ _Outptr_ OrtValue** out);
+
+ /** \brief Get non tensor value count from an ::OrtValue
+ *
+ * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE
+ * the number of elements in the sequence will be returned
+ *
+ * \param[in] value
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out);
+
+ /** \brief Create a map or sequence ::OrtValue
+ *
+ * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s
+ * representing keys and values.<br>
+ *
+ * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the
+ * sequence. 'in' should be an array of N ::OrtValue%s.
+ *
+ * \param[in] in See above for details
+ * \param[in] num_values
+ * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE
+ * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values,
+ enum ONNXType value_type, _Outptr_ OrtValue** out);
+
+ /** \brief Create an opaque (custom user defined type) ::OrtValue
+ *
+ * Constructs an ::OrtValue that contains a value of non-standard type created for
+ * experiments or while awaiting standardization. ::OrtValue in this case would contain
+ * an internal representation of the Opaque type. Opaque types are distinguished from
+ * each other by two strings 1) domain and 2) type name. The combination of the two
+ * must be unique, so the type representation is properly identified internally. The combination
+ * must be properly registered from within ORT at both compile/run time or by another API.
+ *
+ * To construct the ::OrtValue pass domain and type names, also a pointer to a data container
+ * the type of which must be known to both ORT and the client program. That data container may or may
+ * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for
+ * verification purposes.
+ *
+ * \param[in] domain_name Null terminated string of the domain name
+ * \param[in] type_name Null terminated string of the type name
+ * \param[in] data_container User pointer Data to populate ::OrtValue
+ * \param[in] data_container_size Size in bytes of what `data_container` points to
+ * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name,
+ _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out);
+
+ /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue
+ *
+ * Copies internal data from an opaque value into a user provided buffer
+ *
+ * \see OrtApi::CreateOpaqueValue
+ *
+ * \param[in] domain_name Null terminated string of the domain name
+ * \param[in] type_name Null terminated string of the type name
+ * \param[in] in The opaque ::OrtValue
+ * \param[out] data_container Buffer to copy data into
+ * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in,
+ _Out_ void* data_container, size_t data_container_size);
+
+ /// @}
+ /// \name OrtKernelInfo
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Get a float stored as an attribute in the graph node
+ *
+ * \param[in] info ::OrtKernelInfo instance
+ * \param[in] name Null terminated string of the name of the attribute
+ * \param[out] out Pointer to memory where the attribute will be stored
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name,
+ _Out_ float* out);
+
+ /** \brief Fetch a 64-bit int stored as an attribute in the graph node
+ *
+ * \param[in] info ::OrtKernelInfo instance
+ * \param[in] name Null terminated string of the name of the attribute
+ * \param[out] out Pointer to memory where the attribute will be stored
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name,
+ _Out_ int64_t* out);
+
+ /** \brief Fetch a string stored as an attribute in the graph node
+ *
+ * If `out` is nullptr, the value of `size` is set to the true size of the string
+ * attribute, and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the actual string attribute's size,
+ * the value of `size` is set to the true size of the string attribute, the provided memory
+ * is filled with the attribute's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string attribute's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string attribute
+ * and a failure status is returned.)
+ *
+ * \param[in] info ::OrtKernelInfo instance
+ * \param[in] name Null terminated string of the name of the attribute
+ * \param[out] out Pointer to memory where the attribute will be stored
+ * \param[in,out] size See above comments for details
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out,
+ _Inout_ size_t* size);
+
+ /// @}
+ /// \name OrtKernelContext
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Used for custom operators, get the input count of a kernel
+ *
+ * \see ::OrtCustomOp
+ */
+ ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out);
+
+ /** \brief Used for custom operators, get the output count of a kernel
+ *
+ * \see ::OrtCustomOp
+ */
+ ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out);
+
+ /** \brief Used for custom operators, get an input of a kernel
+ *
+ * The function attempts fetches the input of the kernel. If the input is optional
+ * and not present, the function returns success and out is set to nullptr.
+ *
+ * \param[in] context ::OrtKernelContext instance
+ * \param[in] index See KernelContext_GetInputCount for boundaries check.
+ * \param[out] out OrtValue if the input is present otherwise is set nullptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index,
+ _Out_ const OrtValue** out);
+
+ /** \brief Used for custom operators, get an output of a kernel
+ *
+ * The function attempts fetches the output of the kernel. If the output is optional
+ * and not present, the function returns success and out is set to nullptr.
+ *
+ * \param[in] context ::OrtKernelContext instance
+ * \param[in] index See KernelContext_GetOutputCount for boundaries check.
+ * \param[in] dim_values output dimensions
+ * \param[in] dim_count number of dimensions
+ * \param[out] out a ptr to OrtValue to output otherwise set to nullptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index,
+ _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out);
+
+ /// @}
+ /// \name OrtEnv
+ /// @{
+ ORT_CLASS_RELEASE(Env);
+ /// @}
+ /// \name OrtStatus
+ /// @{
+ ORT_CLASS_RELEASE(Status);
+ /// @}
+ /// \name OrtMemoryInfo
+ /// @{
+ ORT_CLASS_RELEASE(MemoryInfo);
+ /// @}
+ /// \name OrtSession
+ /// @{
+ ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool)
+ /// @}
+ /// \name OrtValue
+ /// @{
+ ORT_CLASS_RELEASE(Value);
+ /// @}
+ /// \name OrtRunOptions
+ /// @{
+ ORT_CLASS_RELEASE(RunOptions);
+ /// @}
+ /// \name OrtTypeInfo
+ /// @{
+ ORT_CLASS_RELEASE(TypeInfo);
+ /// @}
+ /// \name OrtTensorTypeAndShapeInfo
+ /// @{
+ ORT_CLASS_RELEASE(TensorTypeAndShapeInfo);
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+ ORT_CLASS_RELEASE(SessionOptions);
+ /// @}
+ /// \name OrtCustomOpDomain
+ /// @{
+ ORT_CLASS_RELEASE(CustomOpDomain);
+
+ /// @}
+ /// \name OrtTypeInfo
+ /// @{
+
+ /** \brief Get denotation from type information
+ *
+ * Augments ::OrtTypeInfo to return denotations on the type.
+ *
+ * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor.
+ *
+ * \param[in] type_info
+ * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free.
+ * \param[out] len Length in bytes of the string returned in `denotation`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation,
+ _Out_ size_t* len);
+
+ /** \brief Get detailed map information from an ::OrtTypeInfo
+ *
+ * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map.
+ * The OrtMapTypeInfo has additional information about the map's key type and value type.
+ *
+ * This is used by WinML to support model reflection APIs.
+ *
+ * \param[out] type_info
+ * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info
+ * does not contain a map, this value will be set to nullptr.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info,
+ _Outptr_result_maybenull_ const OrtMapTypeInfo** out);
+
+ /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo
+ *
+ * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence.
+ * The ::OrtSequenceTypeInfo has additional information about the sequence's element type.
+ *
+ * This is used by WinML to support model reflection APIs.
+ *
+ * \param[in] type_info
+ * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info
+ * doesn not contain a sequence, this value will be set to nullptr.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info,
+ _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out);
+
+ /// @}
+ /// \name OrtMapTypeInfo
+ /// @{
+
+ /** \brief Get key type from an ::OrtMapTypeInfo
+ *
+ * Key types are restricted to being scalar types.
+ *
+ * This is used by WinML to support model reflection APIs.
+ *
+ * \param[in] map_type_info
+ * \param[out] out
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out);
+
+ /** \brief Get the value type from an ::OrtMapTypeInfo
+ *
+ * \param[in] map_type_info
+ * \param[out] type_info A copy of the OrtTypeInfo for the map value type.
+ * The user must free this value with ReleaseTypeInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info);
+
+ /// @}
+ /// \name OrtSequenceTypeInfo
+ /// @{
+
+ /** \brief Get element type from an ::OrtSequenceTypeInfo
+ *
+ * This is used by WinML to support model reflection APIs.
+ *
+ * \param[in] sequence_type_info
+ * \param[out] type_info A copy of the OrtTypeInfo for the sequence element type.
+ * The user must free this value with ReleaseTypeInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /// @}
+ /// \name OrtMapTypeInfo
+ /// @{
+ ORT_CLASS_RELEASE(MapTypeInfo);
+ /// @}
+ /// \name OrtSequenceTypeInfo
+ /// @{
+ ORT_CLASS_RELEASE(SequenceTypeInfo);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief End profiling and return filename of the profile data
+ *
+ * Profiling is turned on through OrtApi::EnableProfiling
+ *
+ * \param[in] session
+ * \param[in] allocator
+ * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out);
+
+ /** \brief Get ::OrtModelMetadata from an ::OrtSession
+ *
+ * \param[in] session
+ * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out);
+
+ /// @}
+ /// \name OrtModelMetadata
+ /// @{
+
+ /** \brief Get `producer name` from an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /** \brief Get `graph name` from an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /** \brief Get `domain` from an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator,
+ _Outptr_ char** value);
+
+ /** \brief Get `description` from an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[in] key Null terminated string
+ * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator`
+ * `value` will be set to nullptr if the given key is not found in the custom metadata map.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value);
+
+ /** \brief Get version number from an ::OrtModelMetadata
+ *
+ * \param[in] model_metadata
+ * \param[out] value Set to the version number
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value);
+
+ ORT_CLASS_RELEASE(ModelMetadata);
+
+ /// @}
+ /// \name OrtEnv
+ /// @{
+
+ /** \brief Create an OrtEnv
+ *
+ * Create an environment with global threadpools that will be shared across sessions.
+ * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use
+ * its own thread pools.
+ *
+ * \param[in] log_severity_level The log severity level.
+ * \param[in] logid The log identifier.
+ * \param[in] tp_options
+ * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid,
+ _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Use global thread pool on a session
+ *
+ * Disable using per session thread pool and use the shared global threadpool.
+ * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools.
+ *
+ * \param[in] options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options);
+
+ /// @}
+ /// \name OrtThreadingOptions
+ /// @{
+
+ /** \brief Create an ::OrtThreadingOptions
+ *
+ * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out);
+
+ ORT_CLASS_RELEASE(ThreadingOptions);
+
+ /// @}
+ /// \name OrtModelMetadata
+ /// @{
+
+ /**
+ *
+ * \param[in] model_metadata
+ * \param[in] allocator
+ * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`.
+ * The strings and the pointer array must be freed using `allocator`
+ * `keys` will be set to nullptr if the custom metadata map is empty.
+ * \param[out] num_keys Set to the number of elements in the `keys` array
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /**
+ *
+ * Override symbolic dimensions (by specific name strings) with actual values
+ * if known at session initialization time to enable optimizations that can
+ * take advantage of fixed values (such as memory planning, etc)
+ *
+ */
+ ORT_API2_STATUS(AddFreeDimensionOverrideByName,
+ _Inout_ OrtSessionOptions* options, _In_ const char* dim_name,
+ _In_ int64_t dim_value);
+
+ /// @}
+ /// \name Misc
+ /// @{
+
+ /** \brief Get the names of all available providers
+ *
+ * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies.
+ * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options.
+ *
+ * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the
+ * array itself must be freed using OrtApi::ReleaseAvailableProviders
+ * \param[out] provider_length Set to the number of entries in the `out_ptr` array
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length);
+
+ /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail
+ * so you can rely on it in a noexcept code.
+ *
+ * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders.
+ * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr,
+ _In_ int providers_length);
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /** \brief Get the length of a single string in a string tensor
+ *
+ * \param[in] value A string tensor
+ * \param[in] index Index of the string in the tensor
+ * \param[out] out Set to number of bytes of the string element
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out);
+
+ /** \brief Get a single string from a string tensor
+ *
+ * \param[in] value A string tensor
+ * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength.
+ * \param[in] index Index of the string in the tensor
+ * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s);
+
+ /** \brief Set a single string in a string tensor
+ *
+ * \param[in] value A string tensor
+ * \param[in] s A null terminated UTF-8 encoded string
+ * \param[in] index Index of the string in the tensor to set
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Set a session configuration entry as a pair of strings
+ *
+ * If a configuration with same key exists, this will overwrite the configuration with the given config_value.
+ *
+ * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h
+ *
+ * \param[in] options
+ * \param[in] config_key A null terminated string representation of the config key
+ * \param[in] config_value A null terminated string representation of the config value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options,
+ _In_z_ const char* config_key, _In_z_ const char* config_value);
+
+ /// @}
+ /// \name OrtAllocator
+ /// @{
+
+ /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo
+ *
+ * The allocator wraps the internal allocator from the OrtSession and becomes invalid when the session does.
+ *
+ * \param[in] session
+ * \param[in] mem_info valid ::OrtMemoryInfo instance
+ * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info,
+ _Outptr_ OrtAllocator** out);
+
+ /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator
+ */
+ ORT_CLASS_RELEASE(Allocator);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief Run a model using Io Bindings for the inputs & outputs
+ *
+ * \see OrtApi::Run
+ *
+ * \param[in] session
+ * \param[in] run_options
+ * \param[in] binding_ptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr);
+
+ /** \brief Create an ::OrtIoBinding instance
+ *
+ * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names.
+ * Thus if you want to use a raw on device buffer as input or output you can avoid
+ * extra copy during runtime.
+ *
+ * \param[in] session
+ * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out);
+
+ /// @}
+ /// \name OrtIoBinding
+ /// @{
+
+ /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding
+ */
+ ORT_CLASS_RELEASE(IoBinding);
+
+ /** \brief Bind an ::OrtValue to an ::OrtIoBinding input
+ *
+ * When using OrtApi::RunWithBinding this value is used for the named input
+ *
+ * \param[in] binding_ptr
+ * \param[in] name Name for the model input
+ * \param[in] val_ptr ::OrtValue of Tensor type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr);
+
+ /** \brief Bind an ::OrtValue to an ::OrtIoBinding output
+ *
+ * When using OrtApi::RunWithBinding this value is used for the named output
+ *
+ * \param[in] binding_ptr
+ * \param[in] name Null terminated string of the model output name
+ * \param[in] val_ptr ::OrtValue of Tensor type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr);
+
+ /** \brief Bind an ::OrtIoBinding output to a device
+ *
+ * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo.
+ * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using
+ * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of
+ * memory within ::OrtValue ahead of time.
+ *
+ * \see OrtApi::RunWithBinding
+ *
+ * \param[in] binding_ptr
+ * \param[in] name Null terminated string of the device name
+ * \param[in] mem_info_ptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr);
+
+ /** \brief Get the names of an ::OrtIoBinding's outputs
+ *
+ * Returns the names of the outputs in the order they were bound. This is useful after running the model
+ * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if
+ * the order of outputs and their names is not known.
+ *
+ * \param[in] binding_ptr
+ * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths.
+ * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter.
+ * This buffer is allocated using `allocator` and must be freed using it.
+ * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer`
+ * This buffer is allocated using `allocator` and must be freed using it.
+ * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned,
+ * no memory allocation is performed and buffer and lengths are set to nullptr.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator,
+ _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count);
+
+ /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding
+ *
+ * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding
+ * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput
+ * or OrtApi::BindOutputToDevice.
+ *
+ * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed.
+ * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after
+ * all the ::OrtValue%s contained therein are individually released.
+ *
+ * \param[in] binding_ptr
+ * \param[in] allocator Allocator used to allocate output array
+ * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs.
+ * \param[out] output_count Set to number of ::OrtValue%s returned
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator,
+ _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count);
+
+ /** \brief Clears any previously set Inputs for an ::OrtIoBinding
+ */
+ void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
+
+ /** \brief Clears any previously set Outputs for an ::OrtIoBinding
+ */
+ void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL;
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /** \brief Direct memory access to a specified tensor element
+ *
+ * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved
+ *
+ * This function only works for numeric type tensors (No strings, etc).
+ * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd.
+ *
+ * \param[in] value
+ * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape
+ * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape.
+ * \param[out] out Set to a pointer to the element specified
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out);
+
+ /// @}
+ /// \name OrtEnv
+ /// @{
+
+ /** \brief Create an allocator and register it with the ::OrtEnv
+ *
+ * Enables sharing the allocator between multiple sessions that use the same env instance.
+ * Lifetime of the created allocator will be valid for the duration of the environment.
+ * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered.
+ *
+ * See https://onnxruntime.ai/docs/get-started/with-c.html for details.
+ *
+ * \param[in] env ::OrtEnv instance
+ * \param[in] mem_info
+ * \param[in] arena_cfg Pass nullptr for defaults
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info,
+ _In_ const OrtArenaCfg* arena_cfg);
+
+ /** \brief Set language projection
+ *
+ * Set the language projection for collecting telemetry data when Env is created.
+ *
+ * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also.
+ *
+ * \param[in] ort_env
+ * \param[in] projection
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief Return the time that profiling was started
+ *
+ * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns
+ *
+ * \param[in] session
+ * \param[out] out nanoseconds of profiling's start time
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out);
+
+ /// @}
+ /// \name OrtThreadingOptions
+ /// @{
+
+ /** \brief Set global intra-op thread count
+ *
+ * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools
+ *
+ * \param[in] tp_options
+ * \param[in] intra_op_num_threads Number of threads, special values:<br>
+ * 0 = Use default thread count<br>
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads);
+
+ /** \brief Set global inter-op thread count
+ *
+ * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools
+ *
+ * \param[in] tp_options
+ * \param[in] inter_op_num_threads Number of threads, special values:<br>
+ * 0 = Use default thread count<br>
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads);
+
+ /** \brief Set global spin control options
+ *
+ * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools.
+ * Allow spinning of thread pools when their queues are empty. This will set the value for both
+ * inter_op and intra_op threadpools.
+ *
+ * \param[in] tp_options
+ * \param[in] allow_spinning Valid values are 0 or 1.<br>
+ * 0 = It won't spin (recommended if CPU usage is high)<br>
+ * 1 = Threadpool will spin to wait for queue to become non-empty
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Add a pre-allocated initializer to a session
+ *
+ * If a model contains an initializer with a name that is same as the name passed to this call,
+ * ORT will use this initializer instance instead of deserializing one from the model file. This
+ * is useful when you want to share the same initializer across sessions.
+ *
+ * \param[in] options
+ * \param[in] name Null terminated string of the initializer name
+ * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be
+ * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object
+ * to which it is added.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name,
+ _In_ const OrtValue* val);
+
+ /// @}
+ /// \name OrtEnv
+ /// @{
+
+ /**
+ * Create a custom environment with global threadpools and logger that will be shared across sessions.
+ * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use
+ * its own thread pools.
+ *
+ * \param[in] logging_function A pointer to a logging function.
+ * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to
+ * `logging_function`.
+ * \param[in] log_severity_level The log severity level.
+ * \param[in] logid The log identifier.
+ * \param[in] tp_options
+ * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level,
+ _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Append CUDA provider to session options
+ *
+ * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] cuda_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA,
+ _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options);
+
+ /** \brief Append ROCM execution provider to the session options
+ *
+ * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] rocm_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM,
+ _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options);
+
+ /** \brief Append OpenVINO execution provider to the session options
+ *
+ * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail.
+ *
+ * \param[in] options
+ * \param[in] provider_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO,
+ _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options);
+
+ /// @}
+ /// \name OrtThreadingOptions
+ /// @{
+
+ /** \brief Set threading flush-to-zero and denormal-as-zero
+ *
+ * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools.
+ * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool.
+ * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy.
+ *
+ * \param[in] tp_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options);
+
+ /// @}
+ /// \name OrtArenaCfg
+ /// @{
+
+ /** \deprecated Use OrtApi::CreateArenaCfgV2
+ *
+ * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior
+ *
+ * \param[in] max_mem Use 0 to allow ORT to choose the default
+ * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested
+ * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default
+ * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default
+ * \param[in] out A pointer to an OrtArenaCfg instance
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes,
+ int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out);
+
+ ORT_CLASS_RELEASE(ArenaCfg);
+
+ /// @}
+ /// \name OrtModelMetadata
+ /// @{
+
+ /**
+ * Use this to obtain the description of the graph present in the model
+ * (doc_string field of the GraphProto message within the ModelProto message).
+ * If it doesn't exist, an empty string will be returned.
+ *
+ * \param[in] model_metadata An instance of ::OrtModelMetadata
+ * \param[in] allocator Allocator used to allocate the string that will be returned back
+ * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator`
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** value);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Append TensorRT provider to session options
+ *
+ * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] tensorrt_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT,
+ _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options);
+
+ /// @}
+ /// \name Misc
+ /// @{
+
+ /** \brief Set current GPU device ID
+ *
+ * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less
+ * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is
+ * required to restrict execution to a single GPU.
+ *
+ * \param[in] device_id
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id);
+
+ /** \brief Get current GPU device ID
+ *
+ * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm).
+ *
+ * \see OrtApi::SetCurrentGpuDeviceId
+ *
+ * \param[out] device_id
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id);
+
+ /// @}
+ /// \name OrtKernelInfo
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Fetch an array of int64_t values stored as an attribute in the graph node
+ *
+ *
+ * If `out` is nullptr, the value of `size` is set to the true size of the attribute
+ * array's size, and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the actual attribute array's size,
+ * the value of `size` is set to the true size of the attribute array's size,
+ * the provided memory is filled with the attribute's contents,
+ * and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual attribute array's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the attribute array's size
+ * and a failure status is returned.)
+ *
+ * \param[in] info instance
+ * \param[in] name name of the attribute to be parsed
+ * \param[out] out pointer to memory where the attribute's contents are to be stored
+ * \param[in, out] size actual size of attribute array
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name,
+ _Out_ float* out, _Inout_ size_t* size);
+
+ /** \brief Fetch an array of int64_t values stored as an attribute in the graph node
+ *
+ * If `out` is nullptr, the value of `size` is set to the true size of the attribute
+ * array's size, and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the actual attribute array's size,
+ * the value of `size` is set to the true size of the attribute array's size,
+ * the provided memory is filled with the attribute's contents,
+ * and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual attribute array's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the attribute array's size
+ * and a failure status is returned.)
+ *
+ * \param[in] info instance
+ * \param[in] name name of the attribute to be parsed
+ * \param[out] out pointer to memory where the attribute's contents are to be stored
+ * \param[in, out] size actual size of attribute array
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name,
+ _Out_ int64_t* out, _Inout_ size_t* size);
+
+ /// @}
+ /// \name OrtArenaCfg
+ /// @{
+
+ /** \brief Create an ::OrtArenaCfg
+ *
+ * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior.
+ *
+ * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the
+ * following parameters mean and how to choose these values.):
+ * "max_mem": Maximum memory that can be allocated by the arena based allocator.
+ * Use 0 for ORT to pick the best value. Default is 0.
+ * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested.
+ * Use -1 to allow ORT to choose the default.
+ * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena.
+ * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default.
+ * Ultimately, the first allocation size is determined by the allocation memory request.
+ * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after
+ * crossing which the current chunk is chunked into 2.
+ * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena.
+ * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default.
+ * "max_power_of_two_extend_bytes": The maximum extend size if arena strategy is `kNextPowerOfTwo`.
+ * It is not an allocation limit, it is only a limit for extension when requested byte is less than the limit.
+ * When requested bytes is more than the limit, allocator will still return as requested.
+ * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes.
+ * Ultimately, the allocation size is determined by the allocation memory request.
+ * Further allocation sizes are governed by the arena extend strategy.
+ *
+ * \param[in] arena_config_keys Keys to configure the arena
+ * \param[in] arena_config_values Values to configure the arena
+ * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values`
+ * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys,
+ _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys,
+ _Outptr_ OrtArenaCfg** out);
+
+ /// @}
+ /// \name OrtRunOptions
+ /// @{
+
+ /** \brief Set a single run configuration entry as a pair of strings
+ *
+ * If a configuration with same key exists, this will overwrite the configuration with the given config_value
+ *
+ * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h
+ *
+ * \param[in] options
+ * \param[in] config_key A null terminated string representation of the config key
+ * \param[in] config_value A null terminated string representation of the config value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options,
+ _In_z_ const char* config_key, _In_z_ const char* config_value);
+
+ /// @}
+ /// \name OrtPrepackedWeightsContainer
+ /// @{
+
+ /** \brief Create an ::OrtPrepackedWeightsContainer
+ *
+ * This container will hold pre-packed buffers of shared initializers for sharing between sessions
+ * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers
+ * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container
+ * to sessions that you would like to share pre-packed buffers of shared initializers at session
+ * creation time.
+ *
+ * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out);
+
+ /** \brief Release OrtPrepackedWeightsContainer instance
+ *
+ * \note instance must not be released until the sessions using it are released
+ */
+ ORT_CLASS_RELEASE(PrepackedWeightsContainer);
+
+ /// @}
+ /// \name OrtSession
+ /// @{
+
+ /** \brief Create session with prepacked weights container
+ *
+ * Same functionality offered by OrtApi::CreateSession except that a container that contains
+ * pre-packed weights' buffers is written into/read from by the created session.
+ * This is useful when used in conjunction with OrtApi::AddInitializer which injects
+ * shared initializer info into sessions. Wherever possible, the pre-packed versions of these
+ * shared initializers are cached in this container so that multiple sessions can just re-use
+ * these instead of duplicating these in memory.
+ *
+ * \param[in] env OrtEnv instance instance
+ * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise)
+ * \param[in] options
+ * \param[in] prepacked_weights_container
+ * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path,
+ _In_ const OrtSessionOptions* options,
+ _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container,
+ _Outptr_ OrtSession** out);
+
+ /** \brief Create session from memory with prepacked weights container
+ *
+ * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains
+ * pre-packed weights' buffers is written into/read from by the created session.
+ * This is useful when used in conjunction with OrtApi::AddInitializer which injects
+ * shared initializer info into sessions. Wherever possible, the pre-packed versions of these
+ * shared initializers are cached in this container so that multiple sessions can just re-use
+ * these instead of duplicating these in memory.
+ *
+ * \param[in] env
+ * \param[in] model_data Array of bytes holding the model
+ * \param[in] model_data_length Number of bytes in `model_data_model`
+ * \param[in] options
+ * \param[in] prepacked_weights_container
+ * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env,
+ _In_ const void* model_data, size_t model_data_length,
+ _In_ const OrtSessionOptions* options,
+ _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container,
+ _Outptr_ OrtSession** out);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Append TensorRT execution provider to the session options
+ *
+ * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure.
+ *
+ * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an
+ * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2
+ * which must be created with OrtApi::CreateTensorRTProviderOptions.
+ *
+ * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions
+ * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions.
+ * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you.
+ *
+ * \param[in] options
+ * \param[in] tensorrt_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2,
+ _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options);
+
+ /// @}
+ /// \name OrtTensorRTProviderOptionsV2
+ /// @{
+
+ /** \brief Create an OrtTensorRTProviderOptionsV2
+ *
+ * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out);
+
+ /** \brief Set options in a TensorRT Execution Provider.
+ *
+ * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc
+ * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2
+ * and value should be its related range. Recreates the options and only sets the supplied values.
+ *
+ * For example, key="trt_max_workspace_size" and value="2147483648"
+ *
+ * \param[in] tensorrt_options
+ * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys
+ * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values
+ * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /** \brief Get serialized TensorRT provider options string.
+ *
+ * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......"
+ *
+ * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance
+ * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions
+ * the specified allocator will be used to allocate continuous buffers for output strings and lengths.
+ * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr);
+
+ /** \brief Release an ::OrtTensorRTProviderOptionsV2
+ *
+ * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does
+ */
+ void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Enable custom operators
+ *
+ * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options);
+
+ /// @}
+ /// \name OrtAllocator
+ /// @{
+
+ /** \brief Register a custom allocator
+ *
+ * Enables sharing between multiple sessions that use the same env instance.
+ * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered.
+ *
+ * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except
+ * instead of ORT creating an allocator based on provided info, in this case
+ * ORT uses the user-provided custom allocator.
+ * See https://onnxruntime.ai/docs/get-started/with-c.html for details.
+ *
+ * \param[in] env
+ * \param[in] allocator User provided allocator
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator);
+
+ /** \brief Unregister a custom allocator
+ *
+ * It is an error if you provide an ::OrtMemoryInfo not corresponding to any
+ * registered allocators for sharing.
+ *
+ * \param[in] env
+ * \param[in] mem_info
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env,
+ _In_ const OrtMemoryInfo* mem_info);
+
+ /// @}
+ /// \name OrtValue
+ /// @{
+
+ /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise
+ *
+ * \param[in] value existing ::OrtValue
+ * \param[out] out unless an error occurs, contains 1 iff the value contains an instance
+ * of sparse tensor or 0 otherwise.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out);
+
+ /** \brief Create an ::OrtValue with a sparse tensor that is empty.
+ *
+ * Use FillSparseTensor<Format>() functions to populate sparse tensor with non-zero values and
+ * format specific indices data.
+ * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value
+ * if any was allocated.
+ * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed
+ * by FillSparseTensor<Format>() APIs. The lifespan of the allocator instance must eclipse the lifespan
+ * this sparse tensor instance as the same allocator will be used to free memory.
+ * \param[in] dense_shape shape of the original dense tensor
+ * \param[in] dense_shape_len number of shape dimensions being passed
+ * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx
+ * \param[out] out Should be freed by calling ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape,
+ size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out);
+
+ /**
+ * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue.
+ * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation.
+ * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue.
+ *
+ * \param[in,out] ort_value ::OrtValue to populate with data
+ * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified
+ * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed.
+ * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer.
+ * \param[in] values_shape pointer to values shape array
+ * \param[in] values_shape_len length of the values_shape
+ * \param[in] values pointer to an array of values. For strings, pass const char**.
+ * \param[in] indices_data pointer to a location of COO indices
+ * \param[in] indices_num number of COO indices
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info,
+ _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values,
+ _In_ const int64_t* indices_data, size_t indices_num);
+
+ /**
+ * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue.
+ * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation.
+ * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue.
+ *
+ * \param[in,out] ort_value ::OrtValue to populate with data
+ * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified
+ * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed.
+ * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer.
+ * \param[in] values_shape pointer to values shape array
+ * \param[in] values_shape_len length of the values_shape
+ * \param[in] values - pointer to an array of values. For strings, pass const char**.
+ * \param[in] inner_indices_data pointer to a location of CSR inner indices
+ * \param[in] inner_indices_num number of CSR inner indices
+ * \param[in] outer_indices_data pointer to a location of CSR outer indices
+ * \param[in] outer_indices_num number of CSR outer indices
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info,
+ _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values,
+ _In_ const int64_t* inner_indices_data, size_t inner_indices_num,
+ _In_ const int64_t* outer_indices_data, size_t outer_indices_num);
+
+ /**
+ * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue.
+ * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation.
+ * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue.
+ *
+ * \param[in,out] ort_value ::OrtValue to populate with data
+ * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified
+ * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed.
+ * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer.
+ * \param[in] values_shape
+ * \param[in] values_shape_len
+ * \param[in] values structure with values information
+ * \param[in] indices_shape_data pointer to a location of indices shape
+ * \param[in] indices_shape_len length of the block sparse indices shape
+ * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info,
+ _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values,
+ _In_ const int64_t* indices_shape_data, size_t indices_shape_len,
+ _In_ const int32_t* indices_data);
+
+ /**
+ * Create an ::OrtValue with a sparse tensor. This is the first step.
+ * Next, use Use<Format>Indices() functions to supply sparse tensor with
+ * format specific indices data and set its sparse format to a specific enum value.
+ * This will not perform memory allocations. It will
+ * use supplied user buffer which should outlive the created sparse tensor.
+ * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer.
+ * This function can not be used to map strings from the user allocated memory. Strings must always be copied
+ * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data
+ * using appropriate Make*() function.
+ *
+ * \param[in] info memory info where sparse values reside.
+ * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero
+ * values, pass nullptr
+ * \param[in] dense_shape shape of the original dense tensor
+ * \param[in] dense_shape_len number of shape dimensions being passed
+ * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values,
+ * pass {0} shape.
+ * \param[in] values_shape_len number of values shape dimensions
+ * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx
+ * \param[out] out Should be freed by calling ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data,
+ _In_ const int64_t* dense_shape, size_t dense_shape_len,
+ _In_ const int64_t* values_shape, size_t values_shape_len,
+ ONNXTensorElementDataType type, _Outptr_ OrtValue** out);
+
+ /**
+ * This assigns Coo format indices to the SparseTensor that was created by
+ * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to
+ * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of
+ * indices_data buffer should eclipse the life span of this ::OrtValue.
+ *
+ * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue
+ * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors.
+ * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal
+ * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or
+ * be twice as number of nnz values for a 2-D indices {nnz, 2}
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num);
+
+ /**
+ * The assigns CSR format indices to the SparseTensor that was created by
+ * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to
+ * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of
+ * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue.
+ *
+ * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue
+ * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors.
+ * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal
+ * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue.
+ * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors.
+ * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or
+ * equal to rows + 1 of the dense shape.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num,
+ _Inout_ int64_t* outer_data, size_t outer_num);
+
+ /**
+ * The assigns BlockSparse format indices to the SparseTensor that was created by
+ * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to
+ * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of
+ * indices_data buffer must eclipse the lifespan of this ::OrtValue.
+ *
+ * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue
+ * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors
+ * \param[in] indices_shape_len length of the indices shape
+ * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data);
+
+ /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor.
+ *
+ * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor
+ * \param[out] out pointer to out parameter
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out);
+
+ /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor.
+ *
+ * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor
+ * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out);
+
+ /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*().
+ *
+ * \param[in] ort_value an instance of ::OrtValue containing sparse tensor
+ * \param[out] out returns a pointer to values data. Do not attempt to free this ptr.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out);
+
+ /** \brief Returns data type, shape for the type of indices specified by indices_format.
+ *
+ * \param[in] ort_value ::OrtValue containing sparse tensor.
+ * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse
+ * tensor does not contain.
+ * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out);
+
+ /** \brief Returns indices data for the type of the indices specified by indices_format
+ *
+ * \param[in] ort_value ::OrtValue containing sparse tensor.
+ * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain.
+ * \param[out] num_indices Pointer to where the number of indices entries is returned
+ * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices);
+ /// @}
+ /// \name OrtSessionOptions
+ /// @{
+
+ /**
+ * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None)
+ * Use this API to find if the optional type OrtValue is None or not.
+ * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue.
+ * For example, if you get an OrtValue that corresponds to Optional(tensor) and
+ * if HasValue() returns true, use it as tensor and so on.
+
+ * \param[in] value Input OrtValue.
+ * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out);
+
+ /// @}
+ /// \name OrtKernelContext
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel
+ * \see ::OrtCustomOp
+ * \param[in] context OrtKernelContext instance
+ * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel.
+ * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to
+ * some other EP), then a nullptr is returned as the output param.
+ * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session.
+ * Only use it for custom kernel launching.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out);
+
+ /// @}
+ /// \name GetTensorMemoryInfo
+ /// @{
+ /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor
+ * \param[in] value ::OrtValue containing tensor.
+ * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info);
+
+ /// @}
+ /// \name GetExecutionProviderApi
+ /// @{
+ /** \brief Get a pointer to the requested version of the Execution Provider specific
+ * API extensions to the OrtApi
+ * \param[in] provider_name The name of the execution provider name. Currently only the following
+ * values are supported: "DML".
+ * \param[in] version Must be ::ORT_API_VERSION.
+ * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure.
+ * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML".
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api);
+
+ /// @}
+
+ /// \name SessionOptions
+ /// @{
+ /** \brief Set custom thread creation function
+ *
+ * \param[in] options Session options
+ * \param[in] ort_custom_create_thread_fn Custom thread creation function
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn);
+
+ /** \brief Set creation options for custom thread
+ *
+ * \param[in] options Session options
+ * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options);
+
+ /** \brief Set custom thread join function
+ *
+ * \param[in] options Session options
+ * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn);
+ /// @}
+
+ /// \name OrtThreadingOptions
+ /// @{
+ /** \brief Set custom thread creation function for global thread pools
+ *
+ * \param[inout] tp_options
+ * \param[in] ort_custom_create_thread_fn Custom thread creation function
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn);
+
+ /** \brief Set custom thread creation options for global thread pools
+ *
+ * \param[inout] tp_options
+ * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr)
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options);
+
+ /** \brief Set custom thread join function for global thread pools
+ *
+ * \param[inout] tp_options
+ * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn);
+ /// @}
+
+ /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda,
+ * in case the system that allocated bound memory operated on a different stream. However, the
+ * operation is provider specific and could be a no-op.
+ *
+ * \param[inout] binding_ptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr);
+
+ /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda,
+ * in case the system that allocated bound memory operated on a different stream. However, the
+ * operation is provider specific and could be a no-op.
+ *
+ * \param[inout] binding_ptr
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr);
+
+ /// \name OrtSessionOptions
+ /// @{
+
+ /** \brief Append CUDA execution provider to the session options
+ *
+ * If CUDA is not available (due to a non CUDA enabled build), this function will return failure.
+ *
+ * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an
+ * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2
+ * which must be created with OrtApi::CreateCUDAProviderOptions.
+ *
+ * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions
+ * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions.
+ * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you.
+ *
+ * \param[in] options
+ * \param[in] cuda_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.11.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2,
+ _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options);
+
+ /// @}
+ /// \name OrtCUDAProviderOptionsV2
+ /// @{
+
+ /** \brief Create an OrtCUDAProviderOptionsV2
+ *
+ * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.11.
+ */
+ ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out);
+
+ /** \brief Set options in a CUDA Execution Provider.
+ *
+ * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options
+ * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2
+ * and value should be its related range. Recreates the options and only sets the supplied values.
+ *
+ * For example, key="device_id" and value="0"
+ *
+ * \param[in] cuda_options
+ * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys
+ * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values
+ * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.11.
+ */
+ ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /**
+ * Get serialized CUDA provider options string.
+ *
+ * For example, "device_id=0;arena_extend_strategy=0;......"
+ *
+ * \param cuda_options - OrtCUDAProviderOptionsV2 instance
+ * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions()
+ * the specified allocator will be used to allocate continuous buffers for output strings and lengths.
+ * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.11.
+ */
+ ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr);
+
+ /** \brief Release an ::OrtCUDAProviderOptionsV2
+ *
+ * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does
+ *
+ * \since Version 1.11.
+ */
+ void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input);
+
+ /// @}
+
+ /** \brief Append MIGraphX provider to session options
+ *
+ * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] migraphx_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.11.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX,
+ _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options);
+
+ /** \brief Replace initialized Tensors with external data with the data provided in initializers.
+ *
+ * The function will find the initialized TensorProtos with external data in the graph with the provided names and
+ * replace them with the provided tensors. The API verifies that the TensorProto being replaced
+ * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement
+ * will occur before any of the optimizations take place. The data will be copied into the graph
+ * since TensorProto can't refer to the user provided buffers.
+ *
+ * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed
+ * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated
+ * and the SessionOptions instance that refers to them can be destroyed.
+ *
+ * \param[in] options
+ * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names.
+ * \param[in] initializers Array of ::OrtValue type
+ * \param[in] num_initializers Number of elements in the initializer_names and initializers
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options,
+ _In_reads_(num_initializers) const char* const* initializer_names,
+ _In_reads_(num_initializers) const OrtValue* const* initializers, size_t num_initializers);
+
+ /** \brief: Create attribute of onnxruntime operator
+ *
+ * \param[in] name Name of the attribute
+ * \param[in] data Data content of the attribute
+ * \param[in] len Number of bytes stored in data for ORT_OP_ATTR_STRING.
+ Number of elements if data represents an array (e.g., ORT_OP_ATTR_INTS). Otherwise, set to 1.
+ * \param[in] type Data type
+ * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(CreateOpAttr,
+ _In_ const char* name,
+ _In_ const void* data,
+ _In_ int len,
+ _In_ OrtOpAttrType type,
+ _Outptr_ OrtOpAttr** op_attr);
+
+ /* \brief: Release op attribute
+ *
+ * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr
+ *
+ * \since Version 1.12.
+ */
+ ORT_CLASS_RELEASE(OpAttr);
+
+ /** \brief: Create onnxruntime native operator
+ *
+ * \param[in] info Kernel info
+ * \param[in] op_name Operator name
+ * \param[in] domain Operator domain
+ * \param[in] version Operator opset version
+ * \param[in] type_constraint_names Name of the type constraints, such as "T" or "T1"
+ * \param[in] type_constraint_values Type of each constraints
+ * \param[in] type_constraint_count Number of constraints
+ * \param[in] attr_values Attributes used to initialize the operator
+ * \param[in] attr_count Number of the attributes
+ * \param[in] input_count Number of inputs
+ * \param[in] output_count Number of outputs
+ * \param[out] ort_op Operator that has been created
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(CreateOp,
+ _In_ const OrtKernelInfo* info,
+ _In_z_ const char* op_name,
+ _In_z_ const char* domain,
+ int version,
+ _In_reads_(type_constraint_count) const char** type_constraint_names,
+ _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values,
+ int type_constraint_count,
+ _In_reads_(attr_count) const OrtOpAttr* const* attr_values,
+ int attr_count,
+ int input_count,
+ int output_count,
+ _Outptr_ OrtOp** ort_op);
+
+ /** \brief: Invoke the operator created by OrtApi::CreateOp
+ * The inputs must follow the order as specified in onnx specification
+ *
+ * \param[in] context Kernel context
+ * \param[in] ort_op Operator that has been created
+ * \param[in] input_values Array of inputs
+ * \param[in] input_count Number of inputs
+ * \param[in] output_values Array of outputs
+ * \param[in] output_count Number of outputs
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(InvokeOp,
+ _In_ const OrtKernelContext* context,
+ _In_ const OrtOp* ort_op,
+ _In_ const OrtValue* const* input_values,
+ _In_ int input_count,
+ _Inout_ OrtValue* const* output_values,
+ _In_ int output_count);
+
+ /* \brief: Release an onnxruntime operator
+ *
+ * \param[in] Op Operator created by OrtApi::CreateOp
+ *
+ * \since Version 1.12.
+ */
+ ORT_CLASS_RELEASE(Op);
+
+ /** \brief: Append execution provider to the session options.
+ * \param[in] options
+ * \param[in] provider_name - provider to add.
+ * \param[in] provider_options_keys - keys to configure the provider options
+ * \param[in] provider_options_values - values to configure the provider options
+ * \param[in] num_keys - number of keys passed in
+ *
+ * Currently supported provider names:
+ * QNNExecutionProvider (or QNN)
+ * OpenVINOExecutionProvider (or OpenVINO)
+ * XnnpackExecutionProvider (or XNNPACK)
+ * WebNNExecutionProvider (or WEBNN)
+ * WebGpuExecutionProvider (or WebGPU)
+ * AzureExecutionProvider (or AZURE)
+ * JsExecutionProvider (or JS)
+ * VitisAIExecutionProvider (or VitisAI)
+ * CoreMLExecutionProvider (or CoreML)
+ *
+ * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_<provider name> function
+ * that should be used to add it.
+ *
+ * QNN supported keys:
+ * "backend_type": Type of QNN backend. Specifies a backend path that is the associated QNN backend library file
+ * name. E.g., given backend type "htp", on Windows, the backend path would be "QnnHtp.dll", and on other
+ * platforms, it would be "libQnnHtp.so". Mutually exclusive with "backend_path".
+ * Available options:
+ * -# "cpu"
+ * -# "gpu"
+ * -# "htp": Default.
+ * -# "saver"
+ * -# "ir"
+ * "backend_path": File path to QNN backend library. Mutually exclusive with "backend_type".
+ * "profiling_level": QNN profiling level.
+ * Available options:
+ * -# "off": Default.
+ * -# "basic"
+ * -# "detailed"
+ * "profiling_file_path": QNN profiling file path if ETW not enabled.
+ * "rpc_control_latency": QNN RPC control latency.
+ * "vtcm_mb": QNN VTCM size in MB. default to 0(not set).
+ * "htp_performance_mode": QNN performance mode.
+ * Available options:
+ * -# "burst"
+ * -# "balanced"
+ * -# "default": Default.
+ * -# "high_performance"
+ * -# "high_power_saver"
+ * -# "low_balanced"
+ * -# "extreme_power_saver"
+ * -# "low_power_saver"
+ * -# "power_saver"
+ * -# "sustained_high_performance"
+ * "dump_qnn_ir_dlc": Use the QnnIr backend library to write .dlc files for each subgraph dispatched to QNN. When
+ * enabled, inference results will be incorrect. Use only for debugging.
+ * -# "0": Default: disabled
+ * -# "1": enabled
+ * "dump_qnn_ir_dlc_dir": Set the directory into which QnnIr will be configured to write QNN graphs as .dlc files.
+ * Default is current working directory.
+ * "qnn_ir_backend_path": File path to the QnnIr backend library. If "dump_qnn_ir_dlc" is enabled, use this path
+ * instead of looking for the Ir backend in the standard location.
+ * "qnn_saver_path": File path to the QNN Saver backend library. If specified, QNN Saver will be enabled and will
+ * dump QNN API calls to disk for replay/debugging. QNN Saver produces incorrect model inference results and
+ * may alter model/EP partitioning. Use only for debugging.
+ * "qnn_context_priority": QNN context priority.
+ * Available options:
+ * -# "low"
+ * -# "normal": Default.
+ * -# "normal_high"
+ * -# "high"
+ * "htp_graph_finalization_optimization_mode": Set the optimization mode for graph finalization on the HTP backend.
+ * Available options:
+ * -# "0": Default.
+ * -# "1": Faster preparation time, less optimal graph.
+ * -# "2": Longer preparation time, more optimal graph.
+ * -# "3": Longest preparation time, most likely even more optimal graph. See QNN SDK documentation for specific
+ * details.
+ * "soc_model": The SoC model number. Refer to the QNN SDK documentation for valid values.
+ * Defaults to "0" (unknown).
+ * "htp_arch": The minimum HTP architecture the driver will use to select compatible QNN operators.
+ * Available options:
+ * -# "0": Default (none).
+ * -# "68"
+ * -# "69"
+ * -# "73"
+ * -# "75"
+ * -# "81"
+ * "device_id": The ID of the device to use when setting 'htp_arch'. Defaults to "0" (for single device).
+ * "enable_htp_fp16_precision": Used for float32 model for HTP backend.
+ * Enable the float32 model to be inferenced with fp16 precision. Otherwise, it will be fp32 precision.
+ * -# "0": With fp32 precision.
+ * -# "1": Default. With fp16 precision.
+ * "offload_graph_io_quantization": Offload graph input quantization and graph output dequantization to another
+ * execution provider (typically CPU EP).
+ * -# "0": Disabled. QNN EP will handle quantization and dequantization of graph I/O.
+ * -# "1": Enabled. This is the default value.
+ * "enable_htp_spill_fill_buffer": Enable HTP spill fill buffer setting. The flag is used while generating context
+ * binary.
+ * -# "0": Default. Disabled.
+ * -# "1": Enabled.
+ * "enable_htp_shared_memory_allocator": Enable the QNN HTP shared memory allocator. Requires libcdsprpc.so/dll to
+ * be available.
+ * -# "0": Default. Disabled.
+ * -# "1": Enabled.
+ * "dump_json_qnn_graph": Set to "1" to dump QNN graphs generated by QNN EP as JSON files. Each graph partition
+ * assigned to QNN EP is dumped to a separate file.
+ * "json_qnn_graph_dir": Directory in which to dump QNN JSON graphs. If not specified, QNN graphs are dumped in the
+ * program's current working directory. Ignored if "dump_json_qnn_graph" is not set.
+ * "op_packages": QNN UDO op_package for QNN EP, allowed format:
+ *   "<op_type>:<op_package_path>:<interface>[:<target>],<op_type2>:<op_package_path2>:<interface2>[:<target>]",
+ *   where op_type is the name of the operation, op_package_path is the path to the op package shared library,
+ * interface is the symbol name to register the op life cycle functions, and target is the backend type. For more
+ * details, refer to: https://docs.qualcomm.com/bundle/publicresource/topics/80-63442-50/op_packages.html
+ * [Advanced] "skip_qnn_version_check": Set to "1" to allow a different version of QNN to be used than what was compiled
+ * into ONNX Runtime. Differences in operator support, accuracy, performance, and QNN's ABI may lead to crashes, inaccurate
+ * results, and poor performance. Use with caution and test thoroughly.
+ *
+ * XNNPACK supported keys:
+ * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider.
+ * default value is 0, which means to use the session thread-pool size.
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options,
+ _In_ const char* provider_name,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /* \brief: Get a copy of kernel info
+ *
+ * \param[in] info Kernel info
+ * \param[out] info_copy Copy of kernel info
+ *
+ * \since Version 1.12.
+ */
+ ORT_API2_STATUS(CopyKernelInfo,
+ _In_ const OrtKernelInfo* info,
+ _Outptr_ OrtKernelInfo** info_copy);
+
+ /* \brief: Release kernel info
+ *
+ * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo
+ *
+ * \since Version 1.12.
+ */
+ ORT_CLASS_RELEASE(KernelInfo);
+
+ /// \name Ort Training
+ /// @{
+ /** \brief Gets the Training C Api struct
+ *
+ * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable
+ * training with onnxruntime.
+ * \note A NULL pointer will be returned and no error message will be printed if the training api
+ * is not supported with this build. A NULL pointer will be returned and an error message will be
+ * printed if the provided version is unsupported, for example when using a runtime older than the
+ * version created with this header file.
+ *
+ * \param[in] version Must be ::ORT_API_VERSION
+ * \return The ::OrtTrainingApi struct for the version requested.
+ *
+ * \since Version 1.13
+ */
+ const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION;
+
+ /// @}
+
+ /** \brief Append CANN provider to session options
+ *
+ * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] cann_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.13.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN,
+ _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options);
+
+ /** \brief Create an OrtCANNProviderOptions
+ *
+ * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.13.
+ */
+ ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out);
+
+ /** \brief Set options in a CANN Execution Provider.
+ *
+ * \param[in] cann_options
+ * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys
+ * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values
+ * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.13.
+ */
+ ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /** \brief Get serialized CANN provider options string.
+ *
+ * \param[in] cann_options OrtCANNProviderOptions instance
+ * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator()
+ * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate
+ * continuous buffers for output strings and lengths.
+ * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'.
+ * The caller is responsible for using the same allocator to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.13.
+ */
+ ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options,
+ _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr);
+
+ /** \brief Release an OrtCANNProviderOptions
+ *
+ * \param[in] input The pointer of OrtCANNProviderOptions which will been deleted
+ *
+ * \since Version 1.13.
+ */
+ void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input);
+
+ /* \brief Get OrtDevice type from MemoryInfo
+ *
+ * \since Version 1.14
+ */
+ void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out);
+
+ /* \brief Update the OrtEnv instance with custom log severity level
+ *
+ * \param[in] ort_env The OrtEnv instance being used
+ * \param[in] log_severity_level The log severity level.
+ *
+ * \since Version 1.14.
+ */
+ ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level);
+
+ /* \brief Set affinities for intra op threads
+ *
+ * Affinity string follows format:
+ * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id
+ * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to.
+ * e.g. 1,2,3;4,5
+ * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th.
+ * To ease the configuration, an "interval" is also allowed:
+ * e.g. 1-8;8-16;17-24
+ * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth.
+ * Note:
+ * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1,
+ * ort does not set affinity on the main thread which is started and managed by the calling app;
+ * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors,
+ * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group.
+ * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary.
+ *
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string);
+
+ /** \brief Register custom ops from a shared library.
+ *
+ * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point:
+ * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api);
+ * It then passes in the provided session options to this function along with the api base.
+ *
+ * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the
+ * library handle is released. If no OrtSession is created, then the library handle is released when the provided
+ * OrtSessionOptions is released.
+ *
+ * \param[in] options The session options.
+ * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library
+ * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information
+ * on the format of library names and search paths.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name);
+
+ /** \brief Register custom ops by calling a RegisterCustomOpsFn function.
+ *
+ * Searches for registration_func_name and if found calls it.
+ *
+ * The library containing the function must either be linked against or previously loaded by the executable.
+ *
+ * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2.
+ *
+ * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load
+ * the library from a path. e.g. mobile platforms where the library must be linked into the app.
+ *
+ * The registration function must have the signature of RegisterCustomOpsFn:
+ * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api);
+ *
+ * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration
+ * function should be implemented.
+ *
+ * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the
+ * registration function.
+ * \param[in] registration_func_name Name of registration function to use.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options,
+ _In_ const char* registration_func_name);
+
+ /// \name OrtKernelInfo
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Get the number of inputs from ::OrtKernelInfo.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs
+ * during kernel/session creation.
+ *
+ * \param[in] info Instance of ::OrtKernelInfo.
+ * \param[out] out Pointer to variable assigned with the result on success.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out);
+
+ /** \brief Get the number of outputs from ::OrtKernelInfo.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs
+ * during kernel/session creation.
+ *
+ * \param[in] info Instance of ::OrtKernelInfo.
+ * \param[out] out Pointer to variable assigned with the result on success.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out);
+
+ /** \brief Get the name of a ::OrtKernelInfo's input.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query an input's name
+ * during kernel/session creation.
+ *
+ * If `out` is nullptr, the value of `size` is set to the size of the name
+ * string (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the name string's size and `out` is not nullptr,
+ * the value of `size` is set to the true size of the string (including null-terminator),
+ * the provided memory is filled with the string's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string
+ * and a failure status is returned.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds.
+ * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name.
+ * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_opt_ char* out,
+ _Inout_ size_t* size);
+
+ /** \brief Get the name of a ::OrtKernelInfo's output.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query an output's name
+ * during kernel/session creation.
+ *
+ * If `out` is nullptr, the value of `size` is set to the size of the name
+ * string (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the name string's size and `out` is not nullptr,
+ * the value of `size` is set to the true size of the string (including null-terminator),
+ * the provided memory is filled with the string's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string
+ * and a failure status is returned.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds.
+ * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's
+ * name.
+ * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_opt_ char* out,
+ _Inout_ size_t* size);
+
+ /** \brief Get the type information for a ::OrtKernelInfo's input.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information
+ * of an input during kernel/session creation.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[in] index Which input to get the type information for
+ * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Get the type information for a ::OrtKernelInfo's output.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information
+ * of an output during kernel/session creation.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[in] index Which input to get the type information for
+ * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute.
+ *
+ * \param[in] info ::OrtKernelInfo instance.
+ * \param[in] name UTF-8 null-terminated string representing the attribute's name.
+ * \param[in] allocator Allocator used to allocate the internal tensor state.
+ * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue,
+ * which will also free internal tensor state allocated with the provided allocator.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name,
+ _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out);
+
+ /// @}
+ /// \name OrtSessionOptions
+ /// Custom operator APIs
+ /// @{
+
+ /** \brief Checks if the given session configuration entry exists.
+ *
+ * The config_key formats are defined in onnxruntime_session_options_config_keys.h
+ *
+ * Can be used in a custom operator library to check for session configuration entries
+ * that target one or more custom operators in the library. Example: The config entry
+ * custom_op.myop.some_key targets a custom op named "myop".
+ *
+ * \param[in] options The ::OrtSessionOptions instance.
+ * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key.
+ * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options,
+ _In_z_ const char* config_key, _Out_ int* out);
+
+ /** \brief Get a session configuration value.
+ *
+ * Returns a failure status if the configuration key does not exist.
+ * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h
+ *
+ * If `config_value` is nullptr, the value of `size` is set to the true size of the string
+ * value (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the actual string value's size,
+ * the value of `size` is set to the true size of the string value, the provided memory
+ * is filled with the value's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string value's size and `config_value`
+ * is not nullptr, the value of `size` is set to the true size of the string value
+ * and a failure status is returned.
+ *
+ * Can be used in a custom operator library to get session configuration entries
+ * that target one or more custom operators in the library. Example: The config entry
+ * custom_op.myop.some_key targets a custom op named "myop".
+ *
+ * \param[in] options The session options.
+ * \param[in] config_key A null-terminated UTF-8 string representation of the config key.
+ * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored.
+ * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.14
+ */
+ ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options,
+ _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size);
+
+ /// @}
+
+ /** \brief Append dnnl provider to session options
+ *
+ * If oneDNN is not available, this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] dnnl_options
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl,
+ _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options);
+
+ /** \brief Create an OrtDnnlProviderOptions
+ *
+ * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out);
+
+ /** \brief Set options in a oneDNN Execution Provider.
+ *
+ * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions
+ * and value should be its related range.
+ *
+ * For example, key="use_arena" and value="1"
+ *
+ * \param[in] dnnl_options
+ * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys
+ * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values
+ * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /**
+ * Get serialized oneDNN provider options string.
+ *
+ * For example, "use_arena=1;......"
+ *
+ * \param dnnl_options - OrtDnnlProviderOptions instance
+ * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions()
+ * the specified allocator will be used to allocate continuous buffers for output strings and lengths.
+ * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr);
+
+ /** \brief Release an ::OrtDnnlProviderOptions
+ *
+ * \since Version 1.15.
+ */
+ void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input);
+
+ /// \name OrtKernelInfo
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Get the graph node name from ::OrtKernelInfo.
+ *
+ * If `out` is nullptr, the value of `size` is set to the size of the name
+ * string (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the name string's size and `out` is not nullptr,
+ * the value of `size` is set to the true size of the string (including null-terminator),
+ * the provided memory is filled with the string's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string
+ * and a failure status is returned.
+ *
+ * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name.
+ * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.15
+ */
+ ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_opt_ char* out, _Inout_ size_t* size);
+
+ /** \brief Get the session logger from ::OrtKernelInfo.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log
+ * messages.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.15
+ */
+ ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger);
+
+ /// @}
+ /// \name OrtKernelContext
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Get the runtime logger from ::OrtKernelContext.
+ *
+ * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log
+ * messages during inference.
+ *
+ * \param[in] context An instance of ::OrtKernelContext.
+ * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.15
+ */
+ ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger);
+
+ /// @}
+ /// \name OrtLogger
+ /// Custom operator APIs.
+ /// @{
+
+ /** \brief Logs a message at the given severity level using the provided ::OrtLogger.
+ *
+ * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level
+ * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity
+ * level.
+ *
+ * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger.
+ *
+ * \param[in] logger The ::OrtLogger instance.
+ * \param[in] log_severity_level The message's severity level.
+ * \param[in] message The message to log.
+ * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE.
+ * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__.
+ * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.15
+ */
+ ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level,
+ _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number,
+ _In_z_ const char* func_name);
+
+ /** \brief Get the logging severity level of the ::OrtLogger.
+ *
+ * Can be used in a custom operator to get the logging severity level of the ::OrtLogger associated with
+ * the ::OrtKernelInfo.
+ *
+ * \param[in] logger The ::OrtLogger instance.
+ * \param[out] out Pointer to variable assigned with the logging severity level on success.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.15
+ */
+ ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out);
+
+ /// @}
+
+ /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value.
+ *
+ * \param[in] info ::OrtKernelInfo instance.
+ * \param[in] index The node index.
+ * \param[out] is_constant Is it a constant node input or not.
+ * \param[out] out The OrtValue tensor value.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out);
+
+ /** \brief Get Optional Type information from an ::OrtTypeInfo
+ *
+ * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional.
+ * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value.
+ * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs.
+ * The actual OrtValues that are supplied in place of optional type inputs should contain
+ * specific type that is described by ::OrtOptionalTypeInfo.
+ *
+ * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied
+ * in place of the optional type when creating the actual ::OrtValue).
+ *
+ * \param[in] type_info
+ * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value,
+ * it is owned by OrtTypeInfo instance. When the type_info does not represent
+ * optional type, nullptr is returned in out.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info,
+ _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out);
+
+ /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo.
+ *
+ * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type.
+ * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value.
+ * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs.
+ * The actual OrtValues that are supplied in place of optional type inputs should contain
+ * specific type that is described by the returned ::OrtTypeInfo.
+ *
+ * \param[in] optional_type_info
+ * \param[out] out A copy of ::OrtTypeInfo for what the optional value could be.
+ * The user must free this value with ReleaseTypeInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info,
+ _Outptr_ OrtTypeInfo** out);
+
+ /** \brief Set a single string in a string tensor
+ * Do not zero terminate the string data.
+ *
+ * \param[in] value A string tensor
+ * \param[in] index - flat index of the element
+ * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator)
+ * \param[inout] buffer - address of return value
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ */
+ ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer);
+
+ /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object
+ *
+ * \param[in] context OrtKernelContext instance
+ * \param[in] mem_info OrtMemoryInfo instance
+ * \param[out] out A pointer to OrtAllocator. Must be released with OrtApi::ReleaseAllocator.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.15.
+ */
+ ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out);
+
+ /** \brief Returns a null terminated string of the build info including git info and cxx flags
+ *
+ * \return UTF-8 encoded version string. Do not deallocate the returned buffer.
+ *
+ * \since Version 1.15.
+ */
+ const char*(ORT_API_CALL* GetBuildInfoString)(void);
+
+ /// \name OrtROCMProviderOptions
+ /// @{
+
+ /** \brief Create an OrtROCMProviderOptions
+ *
+ * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out);
+
+ /** \brief Set options in a ROCm Execution Provider.
+ *
+ * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html
+ * to know the available keys and values. Key should be in null terminated string format of the member of
+ * ::OrtROCMProviderOptions and value should be its related range.
+ *
+ * For example, key="device_id" and value="0"
+ *
+ * \param[in] rocm_options
+ * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys
+ * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values
+ * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /**
+ * Get serialized ROCm provider options string.
+ *
+ * For example, "device_id=0;arena_extend_strategy=0;......"
+ *
+ * \param rocm_options - OrtROCMProviderOptions instance
+ * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions()
+ * the specified allocator will be used to allocate continuous buffers for output strings and lengths.
+ * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr);
+
+ /** \brief Release an ::OrtROCMProviderOptions
+ *
+ * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does
+ *
+ * \since Version 1.16.
+ */
+ void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input);
+
+ /** \brief Create an allocator with specific type and register it with the ::OrtEnv
+ * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator
+ * Enables sharing the allocator between multiple sessions that use the same env instance.
+ * Lifetime of the created allocator will be valid for the duration of the environment.
+ * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered.
+ * \param[in] env OrtEnv instance
+ * \param[in] provider_type ExecutionProvider type
+ * \param[in] mem_info OrtMemoryInfo instance
+ * \param[in] arena_cfg Arena configuration
+ * \param[in] provider_options_keys key of the provider options map
+ * \param[in] provider_options_values value of the provider options map
+ * \param[in] num_keys Length of the provider options map
+ */
+ ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type,
+ _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg,
+ _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys);
+
+ /** \brief Run the model asynchronously in a thread owned by intra op thread pool
+ *
+ * \param[in] session
+ * \param[in] run_options If nullptr, will use a default ::OrtRunOptions
+ * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names
+ * \param[in] input Array of ::OrtValue%s of the input values
+ * \param[in] input_len Number of elements in the input_names and inputs arrays
+ * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names
+ * \param[in] output_names_len Number of elements in the output_names and outputs array
+ * \param[out] output OrtValue* array of size output_names_len.
+ * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue.
+ * Later, the output array will be passed to run_async_callback with all null(s) filled with valid
+ * OrtValue pointer(s) allocated by onnxruntime.
+ * NOTE: it is customer's duty to finally release the output array and each of its member,
+ * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer.
+ * \param[in] run_async_callback Callback function on model run completion
+ * \param[in] user_data User data that pass back to run_async_callback
+ */
+ ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options,
+ _In_reads_(input_len) const char* const* input_names,
+ _In_reads_(input_len) const OrtValue* const* input, size_t input_len,
+ _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len,
+ _Inout_updates_all_(output_names_len) OrtValue** output,
+ _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data);
+
+ /**
+ * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'.
+ * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions.
+ *
+ * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer.
+ *
+ * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance
+ * \param key - Name of the provider option
+ * \param value - A pointer to the instance that will be assigned to this provider option
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value);
+
+ /**
+ * Get TensorRT EP provider option where its data type is pointer.
+ * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString.
+ *
+ * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance
+ * \param key - Name of the provider option
+ * \param ptr - A pointer to the instance that is kept by the provider option
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr);
+
+ /**
+ * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'.
+ * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions.
+ *
+ * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer.
+ *
+ * \param cuda_options - OrtCUDAProviderOptionsV2 instance
+ * \param key - Name of the provider option
+ * \param value - A pointer to the instance that will be assigned to this provider option
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value);
+
+ /**
+ * Get CUDA EP provider option where its data type is pointer.
+ * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString.
+ *
+ * \param cuda_options - OrtCUDAProviderOptionsV2 instance
+ * \param key - Name of the provider option
+ * \param ptr - A pointer to the instance that is kept by the provider option
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr);
+
+ /**
+ * Get a EP resource.
+ * E.g. a cuda stream or a cublas handle
+ *
+ * \param context - Kernel context
+ * \param resource_version - Version of the resource
+ * \param resource_id - Type of resource
+ * \param resource - A pointer to returned resource
+ *
+ * \since Version 1.16.
+ */
+ ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resource_version,
+ _In_ int resource_id, _Outptr_ void** resource);
+
+ /** \brief Set user logging function
+ *
+ * By default the logger created by the CreateEnv* functions is used to create the session logger as well.
+ * This function allows a user to override this default session logger with a logger of their own choosing. This way
+ * the user doesn't have to create a separate environment with a custom logger. This addresses the problem when
+ * the user already created an env but now wants to use a different logger for a specific session (for debugging or
+ * other reasons).
+ *
+ * \param[in] options
+ * \param[in] user_logging_function A pointer to a logging function.
+ * \param[in] user_logging_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to
+ * `user_logging_function`. This parameter is optional.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(SetUserLoggingFunction, _Inout_ OrtSessionOptions* options,
+ _In_ OrtLoggingFunction user_logging_function, _In_opt_ void* user_logging_param);
+
+ /**
+ * Get number of input from OrtShapeInferContext
+ *
+ * \param[in] context
+ * \param[out] out The number of inputs
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context, _Out_ size_t* out);
+
+ /**
+ * Get type and shape info of an input
+ *
+ * \param[in] context
+ * \param[in] index The index of the input
+ * \param[out] info Type shape info of the input
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info);
+
+ /**
+ * Get attribute from OrtShapeInferContext. Note that OrtShapeInferContext is a per-node context, one could only read attribute from current node.
+ *
+ * \param[in] context
+ * \param[in] attr_name Name of the attribute
+ * \param[out] attr Handle of the attribute fetched
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context, _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr);
+
+ /**
+ * Set type and shape info of an output
+ *
+ * \param[in] context
+ * \param[in] index The index of the output
+ * \param[out] info Type shape info of the output
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info);
+
+ /**
+ * Set symbolic shape to type shape info
+ *
+ * \param[in] info Type shape info
+ * \param[in] dim_params Symbolic strings
+ * \param[in] dim_params_length Number of strings
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(SetSymbolicDimensions, _In_ OrtTensorTypeAndShapeInfo* info, _In_ const char* dim_params[], _In_ size_t dim_params_length);
+
+ /**
+ * Read contents of an attribute to data
+ *
+ * \param[in] op_attr
+ * \param[in] type Attribute type
+ * \param[out] data Memory address to save raw content of the attribute
+ * \param[in] len Number of bytes allowed to store in data
+ * \param[out] out Number of bytes required to save the data when the call failed, or the real number of bytes saved to data on success
+ *
+ * \note Does not support reading graph attributes. Refer to Node_GetSubgraphs.
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data, _In_ size_t len, _Out_ size_t* out);
+
+ /** \brief Set whether to use deterministic compute.
+ *
+ * Default is false. If set to true, this will enable deterministic compute for GPU kernels where possible.
+ * Note that this most likely will have a performance cost.
+ *
+ * \param[in] options
+ * \param[in] value
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(SetDeterministicCompute, _Inout_ OrtSessionOptions* options, bool value);
+
+ /**
+ * Run fn in parallel
+ *
+ * \param[in] context
+ * \param[in] fn Function accepting usr_data and an integer as iterator
+ * \param[in] total The number of times fn is to be invoked
+ * \param[in] num_batch Number of batches by which the "total" is to be divided in maximum. When zero, there is no limit
+ * \param[in] usr_data User data to be passed back to fn
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(KernelContext_ParallelFor, _In_ const OrtKernelContext* context, _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data);
+
+ /** \brief Append OpenVINO execution provider to the session options
+ *
+ * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail.
+ *
+ * \param[in] options
+ * \param[in] provider_options_keys
+ * \param[in] provider_options_values
+ * \param[in] num_keys
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.17.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO_V2,
+ _In_ OrtSessionOptions* options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /** \brief Append VitisAI provider to session options
+ *
+ * If VitisAI is not available (due to a non VitisAI enabled build, or if VitisAI is not installed on the system), this function will return failure.
+ *
+ * \param[in] options
+ * \param[in] provider_options_keys
+ * \param[in] provider_options_values
+ * \param[in] num_keys
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.18.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_VitisAI,
+ _In_ OrtSessionOptions* options,
+ _In_reads_(num_keys) const char* const* provider_options_keys,
+ _In_reads_(num_keys) const char* const* provider_options_values,
+ _In_ size_t num_keys);
+
+ /** \brief Get scratch buffer from the corresponding allocator under the specific OrtMemoryInfo object.
+ * NOTE: callers are responsible to release this scratch buffer from the corresponding allocator
+ * \param[in] context OrtKernelContext instance
+ * \param[in] mem_info OrtMemoryInfo instance
+ * \param[in] count_or_bytes How many bytes is this scratch buffer
+ * \param[out] out A pointer to the scratch buffer
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.18.
+ */
+ ORT_API2_STATUS(KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out);
+
+ /** \brief Get allocator from KernelInfo for a specific memory type. Please use C API ReleaseAllocator to release out object
+ *
+ * \param[in] info OrtKernelInfo instance
+ * \param[in] mem_type OrtMemType object
+ * \param[out] out A pointer to OrtAllocator
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.18.
+ */
+ ORT_API2_STATUS(KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out);
+
+ /** \brief Replace initialized Tensors with external data with the provided files in memory
+ *
+ * The function will find the initialized TensorProtos with external data in the graph with the provided
+ * external file names and the file content in memory. The API gets the external file name, offset, data length
+ * from TensorProto, and locate the tensor data from the file in memory buffer.
+ * It creates a Tensor to replace the existing Tensor in graph. The replacement
+ * will occur before any of the optimizations take place. The data will be copied into the graph
+ * since TensorProto can't refer to the user provided buffers.
+ *
+ * \param[in] options
+ * \param[in] external_initializer_file_names Array of null terminated UTF-8 encoded strings of the file names
+ * which holds the external initializers.
+ * \param[in] external_initializer_file_buffer_array Array of pointers to the buffer of the file content.
+ * The buffer can be freed after session creation.
+ * \param[in] external_initializer_file_lengths Array of size_t to indicate the length of file content
+ * \param[in] num_external_initializer_files Number of external files
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.18.
+ */
+ ORT_API2_STATUS(AddExternalInitializersFromFilesInMemory, _In_ OrtSessionOptions* options,
+ _In_reads_(num_external_initializer_files) const ORTCHAR_T* const* external_initializer_file_names,
+ _In_reads_(num_external_initializer_files) char* const* external_initializer_file_buffer_array,
+ _In_reads_(num_external_initializer_files) const size_t* external_initializer_file_lengths,
+ size_t num_external_initializer_files);
+
+ /** \brief Create an OrtLoraAdapter
+ *
+ * The function attempts to locate file specified by adapter_file_path, read it and create an OrtLoraAdapter
+ * instance. The adapter_file_path should be a valid path to a file that contains a valid Lora Adapter
+ * format. The function attempts to validate the format at load time. The file will always be memory mapped, unless
+ * the platform does not support memory mapping, in which case the file will be read into memory.
+ *
+ * \param[in] adapter_file_path adapter file path.
+ * \param[in] allocator optional pointer to a device allocator. If specified
+ * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU.
+ * The data would still be copied to device if required by the model at inference time.
+ * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with
+ * OrtApi::ReleaseLoraAdapter.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.20.
+ */
+ ORT_API2_STATUS(CreateLoraAdapter, const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator,
+ _Outptr_ OrtLoraAdapter** out);
+
+ /** \brief Create an OrtLoraAdapter
+ *
+ * The function copies the bytes from the array and creates an OrtLoraAdapter instance.
+ *
+ *
+ * \param[in] bytes pointer to a valid Lora Adapter format buffer.
+ * \param[in] num_bytes length of bytes buffer.
+ * \param[in] allocator optional pointer to a device allocator. If specified
+ * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU.
+ * The data would still be copied to device if required by the model at inference time.
+ * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with
+ * OrtApi::ReleaseLoraAdapter.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.20.
+ */
+ ORT_API2_STATUS(CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator,
+ _Outptr_ OrtLoraAdapter** out);
+
+ /** \brief Release an ::OrtLoraAdapter obtained from OrtApi::CreateLoraAdapter
+ */
+ ORT_CLASS_RELEASE(LoraAdapter);
+
+ /** \brief Add the Lora Adapter to the list of active adapters.
+ *
+ * The function adds the Lora Adapter to the list of active adapters. The Lora Adapter must be created with
+ * OrtApi::CreateLoraAdapter or FromArray. The Lora Adapter will be used by the session to run the model.
+ * The instance of the OrtRunOptions can then be used to customize the Run() calls.
+ * More than one OrtLoraAdapter can be active at the same time. Lora Parameters that belong to different
+ * Lora adapters that will be active at the same time must not overlap.
+ * This setting does not affect RunWithBinding.
+ *
+ * \param[in] options OrtRunOptions instance
+ * \param[in] adapter OrtLoraAdapter instance
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.20.
+ */
+ ORT_API2_STATUS(RunOptionsAddActiveLoraAdapter, _Inout_ OrtRunOptions* options, _In_ const OrtLoraAdapter* adapter);
+
+ /// @}
+ /// \name OrtEpDynamicOptions
+ /// @{
+
+ /** \brief Set DynamicOptions for EPs (Execution Providers)
+ *
+ * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h`
+ * Look for `kOrtEpDynamicOptions`
+ *
+ * \param[in] sess OrtSession
+ * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys
+ * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values
+ * \param[in] kv_len Number of elements in the keys and values arrays
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.20.
+ */
+ ORT_API2_STATUS(SetEpDynamicOptions, _Inout_ OrtSession* sess, _In_reads_(kv_len) const char* const* keys,
+ _In_reads_(kv_len) const char* const* values, _In_ size_t kv_len);
+
+ /// @}
+
+ /** \brief Release an OrtValueInfo instance if it was not added to an OrtGraph.
+ * \since Version 1.22.
+ */
+ ORT_CLASS_RELEASE(ValueInfo);
+
+ /** \brief Release an OrtNode if it was not added to an OrtGraph.
+ * \since Version 1.22.
+ */
+ ORT_CLASS_RELEASE(Node);
+
+ /** \brief Release an OrtGraph.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.22.
+ */
+ ORT_CLASS_RELEASE(Graph);
+
+ /** \brief Release an OrtModel.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.22.
+ */
+ ORT_CLASS_RELEASE(Model);
+
+ /** \brief Get the value name from an OrtValueInfo instance.
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] name The name of the OrtValueInfo
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(GetValueInfoName, _In_ const OrtValueInfo* value_info, _Out_ const char** name);
+
+ /** \brief Get the type information from an OrtValueInfo instance.
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] type_info The type info of the OrtValueInfo
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(GetValueInfoTypeInfo, _In_ const OrtValueInfo* value_info, _Outptr_ const OrtTypeInfo** type_info);
+
+ /** \brief Get the Model Editor API instance
+ *
+ * Get the Model Editor API instance to create a new model or augment an existing model.
+ *
+ * \return Model Editor API struct
+ *
+ * \since Version 1.22.
+ */
+ const OrtModelEditorApi*(ORT_API_CALL* GetModelEditorApi)(void);
+
+ /** \brief Create an OrtValue for a Tensor that uses pre-existing memory.
+ *
+ * ORT will take ownership of the memory and free it using the provided deleter when no longer in use.
+ *
+ * \param[in] deleter OrtAllocator instance that will be used to free the memory.
+ * Only the OrtAllocator:Info and OrtAllocator::Release functions are required.
+ * The OrtMemoryInfo returned by OrtAllocator::Info must match the location of p_data.
+ * \param[in] p_data Pointer to the memory that will be used by the Tensor. ORT will take ownership of the memory.
+ * \param[in] p_data_len Length of the memory in bytes.
+ * \param[in] shape Dimensions of the Tensor. All values should be > 0.
+ * \param[in] shape_len Number of dimensions in the shape array.
+ * \param[in] type Data type of the Tensor.
+ * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateTensorWithDataAndDeleterAsOrtValue, _In_ OrtAllocator* deleter,
+ _In_ void* p_data, size_t p_data_len,
+ _In_ const int64_t* shape, size_t shape_len,
+ ONNXTensorElementDataType type,
+ _Outptr_ OrtValue** out);
+
+ /** \brief sets load cancellation flag to abort session loading process.
+ *
+ * \param[in] options instance that was passed to the session at creation time.
+ * \param[in] cancel setting this to true after model loading process was initiated will
+ * attempt to cancel the loading process. If cancellation is successful, CreateSession()
+ * CreateSessionFromArray() or any other session creation API that take session options as an
+ * argument will return an OrtStatus indicating that session loading was canceled at user request,
+ * error code ORT_MODEL_LOAD_CANCELED.
+ * The APIs above would not return any valid Session instance. This is the best case effort and the result
+ * is not guaranteed. The session may have already been created and initialized
+ * before the cancellation request was issued.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(SessionOptionsSetLoadCancellationFlag, _Inout_ OrtSessionOptions* options,
+ _In_ bool cancel);
+
+ /** \brief Get the Compile API instance.
+ *
+ * Get the Compile API instance to compile ONNX models. Execution providers that support compilation fuse a subgraph
+ * into an EPContext node that wraps a provider-specific binary representation of the subgraph.
+ * For more details about the EPContext design, refer to:
+ * \htmlonly
+ * <a href="https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html">EPContext design document.</a>
+ * \endhtmlonly
+ *
+ * \return Compile API struct instance.
+ *
+ * \since Version 1.22.
+ */
+ const OrtCompileApi*(ORT_API_CALL* GetCompileApi)(void);
+
+ //
+ // OrtKeyValuePairs
+ //
+
+ /** \brief Create an OrtKeyValuePairs instance.
+ *
+ * \param[out] out A pointer to a newly created OrtKeyValuePairs instance.
+ *
+ * \note Must be released by calling ReleaseKeyValuePairs.
+ *
+ * \since Version 1.22.
+ */
+ void(ORT_API_CALL* CreateKeyValuePairs)(_Outptr_ OrtKeyValuePairs** out);
+
+ /** \brief Add a key-value pair to the OrtKeyValuePairs instance.
+ *
+ * If a pair with the same key already exists, it is overwritten.
+ *
+ * \param[in] kvps OrtKeyValuePairs instance.
+ * \param[in] key Key to be added.
+ * \param[in] value Value to be added.
+ *
+ * \note The `key` and `value` are copied internally.
+ *
+ * \since Version 1.22.
+ */
+
+ void(ORT_API_CALL* AddKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key, _In_ const char* value);
+
+ /** \brief Get the value associated with a key in the OrtKeyValuePairs instance.
+ *
+ * \param[in] kvps OrtKeyValuePairs instance.
+ * \param[in] key Key to be searched.
+ *
+ * \return The value associated with the key, or nullptr if the key does not exist.
+ *
+ * \since Version 1.22.
+ */
+ const char*(ORT_API_CALL* GetKeyValue)(_In_ const OrtKeyValuePairs* kvps, _In_ const char* key);
+
+ /** \brief Get all the key-value pairs from the OrtKeyValuePairs instance.
+ *
+ * \param[in] kvps OrtKeyValuePairs instance.
+ * \param[out] keys Array of keys from `kvps`.
+ * \param[out] values Array of values from `kvps`.
+ * \param[out] num_entries Number of entries in `keys` and `values`.
+ *
+ * \since Version 1.22.
+ */
+ void(ORT_API_CALL* GetKeyValuePairs)(_In_ const OrtKeyValuePairs* kvps,
+ _Outptr_ const char* const** keys, _Outptr_ const char* const** values,
+ _Out_ size_t* num_entries);
+
+ /** \brief Remove a key-value pair from the OrtKeyValuePairs instance.
+ *
+ * \param[in] kvps OrtKeyValuePairs instance.
+ * \param[in] key Key to be removed. No error if not found.
+ *
+ * \since Version 1.22.
+ */
+ void(ORT_API_CALL* RemoveKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key);
+
+ /** \brief Release an OrtKeyValuePairs instance.
+ *
+ * \param[in] input OrtKeyValuePairs instance to be released.
+ *
+ * \since Version 1.22.
+ */
+ ORT_CLASS_RELEASE(KeyValuePairs);
+
+ /** \brief Register an execution provider library with ORT.
+ *
+ * The library must export 'CreateEpFactories' and 'ReleaseEpFactory' functions.
+ * See OrtEpApi for more details.
+ *
+ * \param[in] env The OrtEnv instance to register the library in.
+ * \param[in] registration_name The name to register the execution provider library under.
+ * \param[in] path The path to the execution provider library.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(RegisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name,
+ _In_ const ORTCHAR_T* path);
+
+ /** \brief Unregister an execution provider library with ORT.
+ *
+ * ORT will call ReleaseEpFactory for all factories created by the library, and unload the library.
+ *
+ * You <b>MUST</b> ensure there are no Session instances using execution providers created by the library
+ * before calling this function.
+ *
+ * \param[in] env The OrtEnv instance to unregister the library from.
+ * \param[in] registration_name The name the execution provider library was registered under.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(UnregisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name);
+
+ /** \brief Get the list of available OrtEpDevice instances.
+ *
+ * Each OrtEpDevice instance contains details of the execution provider and the device it will use.
+ *
+ * \param[in] env The OrtEnv instance to query.
+ * \param[out] ep_devices The OrtEpDevice instances that the execution provider will use.
+ * \param[out] num_ep_devices The number of OrtEpDevice instances returned.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(GetEpDevices, _In_ const OrtEnv* env,
+ _Outptr_ const OrtEpDevice* const** ep_devices, _Out_ size_t* num_ep_devices);
+
+ /** \brief Append the execution provider that is responsible for the selected OrtEpDevice instances
+ * to the session options.
+ *
+ * \param[in] session_options Session options to add execution provider to.
+ * \param[in] env Environment that execution providers were registered with.
+ * \param[in] ep_devices One or more OrtEpDevice instances to create an execution provider for.
+ * Obtain from GetEpDevices. All OrtEpDevice instances must be from the same execution
+ * provider. It is only necessary to provide multiple OrtEpDevices if you want to use the
+ * same execution provider for multiple devices.
+ * e.g. the EP is capable of running on GPU and NPU.
+ * \param[in] num_ep_devices Number of OrtEpDevice instances.
+ * \param[in] ep_option_keys Optional keys to configure the execution provider.
+ * \param[in] ep_option_vals Optional values to configure the execution provider.
+ * \param[in] num_ep_options Number of execution provide options to add.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_V2, _In_ OrtSessionOptions* session_options,
+ _In_ OrtEnv* env,
+ _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices, _In_ size_t num_ep_devices,
+ _In_reads_(num_op_options) const char* const* ep_option_keys,
+ _In_reads_(num_op_options) const char* const* ep_option_vals,
+ size_t num_ep_options);
+
+ /** \brief Set the execution provider selection policy for the session.
+ *
+ * Allows users to specify a device selection policy for automatic execution provider (EP) selection.
+ * If custom selection is required please use SessionOptionsSetEpSelectionPolicyDelegate instead.
+ *
+ * \param[in] session_options The OrtSessionOptions instance.
+ * \param[in] policy The device selection policy to use (see OrtExecutionProviderDevicePolicy).
+ *
+ * \since Version 1.22
+ */
+ ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicy, _In_ OrtSessionOptions* session_options,
+ _In_ OrtExecutionProviderDevicePolicy policy);
+
+ /** \brief Set the execution provider selection policy delegate for the session.
+ *
+ * Allows users to provide a custom device selection policy for automatic execution provider (EP) selection.
+ *
+ * \param[in] session_options The OrtSessionOptions instance.
+ * \param[in] delegate Delegate callback for custom selection.
+ * \param[in] delegate_state Optional state that will be passed to the delegate callback. nullptr if not required.
+ *
+ * \since Version 1.22
+ */
+ ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicyDelegate, _In_ OrtSessionOptions* session_options,
+ _In_ EpSelectionDelegate delegate,
+ _In_opt_ void* delegate_state);
+
+ /** \brief Get the hardware device type.
+ *
+ * \param[in] device The OrtHardwareDevice instance to query.
+ * \return The hardware device type.
+ *
+ * \since Version 1.22.
+ */
+ OrtHardwareDeviceType(ORT_API_CALL* HardwareDevice_Type)(_In_ const OrtHardwareDevice* device);
+
+ /** \brief Get the hardware device's vendor identifier.
+ *
+ * \param[in] device The OrtHardwareDevice instance to query.
+ * \return The hardware device vendor identifier.
+ *
+ * \since Version 1.22.
+ */
+ uint32_t(ORT_API_CALL* HardwareDevice_VendorId)(_In_ const OrtHardwareDevice* device);
+
+ /** \brief Get the hardware device's vendor name.
+ *
+ * \param[in] device The OrtHardwareDevice instance to query.
+ * \return The hardware device's vendor name.
+ *
+ * \since Version 1.22.
+ */
+ const char*(ORT_API_CALL* HardwareDevice_Vendor)(_In_ const OrtHardwareDevice* device);
+
+ /** \brief Get the hardware device's unique identifier.
+ *
+ * \param[in] device The OrtHardwareDevice instance to query.
+ * \return The device id.
+ *
+ * \note This is not a unique identifier. It identifies the hardware type when combined with vendor id.
+ * \since Version 1.22.
+ */
+ uint32_t(ORT_API_CALL* HardwareDevice_DeviceId)(_In_ const OrtHardwareDevice* device);
+
+ /** \brief Get hardware device metadata.
+ *
+ * \param[in] device The OrtHardwareDevice instance to query.
+ * \return An OrtKeyValuePairs instance containing the metadata for the device.
+ * Note: ORT owns the instance so the user must not call ReleaseKeyValuePairs with it.
+ *
+ * \since Version 1.22.
+ */
+ const OrtKeyValuePairs*(ORT_API_CALL* HardwareDevice_Metadata)(_In_ const OrtHardwareDevice* device);
+
+ /** \brief Get the execution provider name.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \return The execution provider name.
+ *
+ * \since Version 1.22.
+ */
+ const char*(ORT_API_CALL* EpDevice_EpName)(_In_ const OrtEpDevice* ep_device);
+
+ /** \brief Get the execution provider's vendor name.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \return The execution provider's vendor name.
+ *
+ * \since Version 1.22.
+ */
+ const char*(ORT_API_CALL* EpDevice_EpVendor)(_In_ const OrtEpDevice* ep_device);
+
+ /** \brief Get the metadata for the OrtEpDevice.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \return An OrtKeyValuePairs instance containing the metadata for the device.
+ *
+ * \since Version 1.22.
+ */
+ const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpMetadata)(_In_ const OrtEpDevice* ep_device);
+
+ /** \brief Get the execution provider options for the OrtEpDevice.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \return An OrtKeyValuePairs instance containing the execution provider options for the device.
+ *
+ * \since Version 1.22.
+ */
+ const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpOptions)(_In_ const OrtEpDevice* ep_device);
+
+ /** \brief Get the OrtHardwareDevice instance for the OrtEpDevice.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \return The OrtHardwareDevice instance for the device.
+ *
+ * \since Version 1.22.
+ */
+ const OrtHardwareDevice*(ORT_API_CALL* EpDevice_Device)(_In_ const OrtEpDevice* ep_device);
+
+ /** \brief Get the OrtEpApi instance for implementing an execution provider.
+ *
+ * \since Version 1.22.
+ */
+ const OrtEpApi*(ORT_API_CALL* GetEpApi)(void);
+
+ /** \brief Compute total size in bytes of the tensor data contained in an OrtValue.
+ *
+ * Returns the total number of bytes used to store the tensor data. For numeric tensors,
+ * this is sizeof(element_type) * total_element_count. OrtValues that are not tensors or
+ * that are tensors that contain strings will cause an error to be returned.
+ *
+ * \param[in] ort_value OrtValue instance containing a tensor
+ * \param[out] size The total size of the tensor data in bytes
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(GetTensorSizeInBytes, _In_ const OrtValue* ort_value, _Out_ size_t* size);
+
+ /** \brief Calls OrtAllocator::GetStats function
+ *
+ * Return a pointer to the OrtKeyValuePairs structure that contains the statistics of the allocator
+ * and the user should call OrtApi::ReleaseKeyValuePairs.
+ *
+ * NOTE: If the allocator does not implement this function, the OrtKeyValuePairs instance will be empty.
+ *
+ * \param[in] ort_allocator The allocator to get stats from
+ * \param[out] out A pointer to the OrtKeyValuePairs instance that contains the stats
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(AllocatorGetStats, _In_ const OrtAllocator* ort_allocator, _Outptr_ OrtKeyValuePairs** out);
+
+ /** \brief Create an ::OrtMemoryInfo
+ *
+ * \param[in] name Arbitrary name.
+ * \param[in] device_type Device type.
+ * \param[in] vendor_id PCI Vendor ID. Use 0 for a generic allocator (e.g. WebGPU).
+ * \param[in] device_id Device ID if there are multiple devices of the same type. e.g. 2 GPU devices.
+ * \param[in] mem_type Memory type. Use OrtDeviceMemoryType_DEFAULT for device memory, and
+ * OrtDeviceMemoryType_HOST_ACCESSIBLE (if applicable) for memory used to transfer between the
+ * device and the CPU. Use the device_type and device_id of the GPU/NPU that the memory is also
+ * accessible to.
+ * \param[in] alignment Alignment of the memory if required. Pass 0 for default alignment.
+ * \param[in] allocator_type Allocator type. If OrtAllocatorType::OrtArenaAllocator, the ORT arena will be used.
+ * Caveat: Support for OrtArenaAllocator is currently limited to usage of internal ORT
+ * allocators via CreateAllocator/CreateAndRegisterAllocator/CreateAndRegisterAllocatorV2.
+ * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtApi::ReleaseMemoryInfo
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(CreateMemoryInfo_V2, _In_ const char* name, _In_ enum OrtMemoryInfoDeviceType device_type,
+ _In_ uint32_t vendor_id, _In_ int32_t device_id, _In_ enum OrtDeviceMemoryType mem_type,
+ _In_ size_t alignment, enum OrtAllocatorType allocator_type,
+ _Outptr_ OrtMemoryInfo** out);
+
+ /** \brief Get the device memory type from ::OrtMemoryInfo
+ *
+ * \param[in] ptr The OrtMemoryInfo instance to query.
+ * \return The device memory type.
+ *
+ * \since Version 1.23
+ */
+ ORT_API_T(OrtDeviceMemoryType, MemoryInfoGetDeviceMemType, _In_ const OrtMemoryInfo* ptr);
+
+ /** \brief Get the vendor id from ::OrtMemoryInfo
+ *
+ * \param[in] ptr The OrtMemoryInfo instance to query.
+ * \return The vendor id.
+ *
+ * \since Version 1.23
+ */
+ ORT_API_T(uint32_t, MemoryInfoGetVendorId, _In_ const OrtMemoryInfo* ptr);
+
+ /// \name OrtValueInfo
+ /// @{
+
+ /** \brief Get the OrtNode that produces the value represented by the given OrtValueInfo.
+ * Optionally returns the associated output index.
+ *
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] producer_node Output parameter set to the OrtNode that produces the OrtValueInfo.
+ * \param[out] producer_output_index Optional output parameter set to the OrtNode instance's output index
+ * that produces the value. Ignored if set to NULL.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_GetValueProducer, _In_ const OrtValueInfo* value_info,
+ _Outptr_ const OrtNode** producer_node, _Out_opt_ size_t* producer_output_index);
+
+ /** \brief Get the number of consumers of a value as a node input.
+ *
+ * Only nodes are considered "consumers" by this function. To check if an OrtValueInfo is a graph output,
+ * call ValueInfo_IsGraphOutput().
+ *
+ * A single OrtNode may use a single value for more than one input (e.g., Mul(x, x)), so the returned
+ * `num_consumers` may be larger than the number of unique OrtNode instances that consume the value.
+ *
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] num_consumers Output parameter set to the number of consumers of the value.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_GetValueNumConsumers, _In_ const OrtValueInfo* value_info, _Out_ size_t* num_consumers);
+
+ /** \brief Returns information (OrtNode and input index) for all consumer nodes that use the value as an input.
+ *
+ * Only nodes are considered "consumers" by this function.
+ *
+ * Caller provides 2 pre-allocated arrays that will be filled with the OrtNode and input index values.
+ * Use ValueInfo_GetValueNumConsumers() to get the number of consumers of the value.
+ *
+ * An OrtNode instance may appear multiple times if it uses the given value more than once.
+ * Example: For a node MulNode(x, x) that consumes the value 'x' twice, the following is returned:
+ * - nodes: [MulNode, MulNode]
+ * - input_indices: [0, 1]
+ *
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] nodes Pre-allocated array of size `num_consumers` that is filled with OrtNode instances.
+ * \param[out] input_indices Pre-allocated array of `num_consumers` elements that is filled
+ * with input indices. Index is set to -1 for an "implicit" input to a consumer node
+ * that contains a subgraph (e.g., If, Loop) with nodes that use the value internally.
+ * \param[in] num_consumers The size of the `consumer_nodes` and `consumer_input_indices` arrays.
+ * Typical usage sets this to the value of ValueInfo_GetValueNumConsumers().
+ * An error status is returned if `num_consumers` is less than the number of actual
+ * consumers.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_GetValueConsumers, _In_ const OrtValueInfo* value_info,
+ _Out_writes_all_(num_consumers) const OrtNode** nodes,
+ _Out_writes_all_(num_consumers) int64_t* input_indices,
+ _In_ size_t num_consumers);
+
+ /** \brief Get the underlying initializer value, as an OrtValue, from the given OrtValueInfo.
+ *
+ * Sets the output parameter to NULL if the given OrtValueInfo does not represent an initializer.
+ * Does not return an error status in this case.
+ *
+ * Supports initializers defined in an outer scope (i.e., a parent graph).
+ *
+ * Supports initializers stored in an external file. For external initializers, ORT memory maps
+ * the initializer data on the first call to this function. If caller needs custom memory mapping,
+ * use ValueInfo_GetExternalInitializerInfo to get the location of the initializer data.
+ *
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] initializer_value Output parameter set to the initializer value or NULL. Do not cache the OrtValue
+ * as it is released when the owning OrtGraph is released.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_GetInitializerValue, _In_ const OrtValueInfo* value_info,
+ _Outptr_ const OrtValue** initializer_value);
+
+ /** \brief Get information about an external initializer (e.g., filepath, file offset, byte size).
+ *
+ * Sets the output parameter `info` to NULL if the given OrtValueInfo does not represent an initializer
+ * with external data. In this case, a NULL status (non-error) is returned.
+ *
+ * \param[in] value_info The OrtValueInfo instance.
+ * \param[out] info Output parameter set to an OrtExternalInitializerInfo instance that can be used to query
+ * file path, file offset, etc. ORT sets this to NULL if the OrtValueInfo does not represent
+ * an external initializer.
+ * Must release with ReleaseExternalInitializerInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_GetExternalInitializerInfo, _In_ const OrtValueInfo* value_info,
+ _Outptr_result_maybenull_ OrtExternalInitializerInfo** info);
+
+ /** \brief Returns a boolean indicating if the given value is a required graph input.
+ *
+ * For ONNX IR version < 4, all graph inputs without a matching initializer are required.
+ *
+ * For ONNX IR version >=4, a graph input with a matching initializer is an optional graph input
+ * with the initializer serving as the default value.
+ *
+ * \param[in] value_info The OrtValueInfo instance representing the graph value.
+ * \param[out] is_required_graph_input Output parameter set to true if the graph value is a required graph input.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_IsRequiredGraphInput, _In_ const OrtValueInfo* value_info,
+ _Out_ bool* is_required_graph_input);
+
+ /** \brief Returns a boolean indicating if the given value is an optional graph input.
+ *
+ * Optional graph inputs were introduced in ONNX IR version 4. For ONNX IR version >=4, a graph input with a
+ * matching initializer is an optional graph input with the initializer serving as the default value.
+ * The matching initializer is also known as a non-constant initializer.
+ *
+ * \param[in] value_info The OrtValueInfo instance representing the graph value.
+ * \param[out] is_optional_graph_input Output parameter set to true if the graph value is an optional graph input.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_IsOptionalGraphInput, _In_ const OrtValueInfo* value_info,
+ _Out_ bool* is_optional_graph_input);
+
+ /** \brief Returns a boolean indicating if the given value is a graph output.
+ *
+ * \param[in] value_info The OrtValueInfo instance representing the graph value.
+ * \param[out] is_graph_output Output parameter set to true if the graph value is a graph output.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_IsGraphOutput, _In_ const OrtValueInfo* value_info, _Out_ bool* is_graph_output);
+
+ /** \brief Returns a boolean indicating if the given value is a constant initializer.
+ *
+ * For ONNX IR version < 4, all initializers are constant.
+ *
+ * For ONNX IR version >=4, an initializer that serves as the default value for a matching graph input is not a
+ * constant initializer.
+ *
+ * \param[in] value_info The OrtValueInfo instance representing the graph value.
+ * \param[out] is_constant_initializer Output parameter set to true if the graph value is a constant initializer.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_IsConstantInitializer, _In_ const OrtValueInfo* value_info,
+ _Out_ bool* is_constant_initializer);
+
+ /** \brief Returns a boolean indicating if the given value is defined in an outer scope.
+ *
+ * Certain operator types (e.g., If and Loop) contain nested subgraphs. This function enables
+ * determining whether a value is defined in a parent node's graph.
+ *
+ * \param[in] value_info The OrtValueInfo instance representing the graph value.
+ * \param[out] is_from_outer_scope Output parameter set to true if the value is defined in an outer
+ * scope (i.e., a parent graph).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValueInfo_IsFromOuterScope, _In_ const OrtValueInfo* value_info,
+ _Out_ bool* is_from_outer_scope);
+
+ /// @}
+
+ /// \name OrtGraph
+ /// @{
+
+ /** \brief Returns a graph's name.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] graph_name Output parameter set to the graph's name.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetName, _In_ const OrtGraph* graph, _Outptr_ const char** graph_name);
+
+ /** \brief Get the filepath to the model from which an OrtGraph is constructed.
+ *
+ * \note The model's filepath is empty if the filepath is unknown, such as when the model is loaded from bytes
+ * via CreateSessionFromArray.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] model_path Output parameter set to the model's null-terminated filepath.
+ * Set to an empty path string if unknown.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetModelPath, _In_ const OrtGraph* graph, _Outptr_ const ORTCHAR_T** model_path);
+
+ /** \brief Returns the ONNX IR version.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] onnx_ir_version Output parameter set to the ONNX IR version.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetOnnxIRVersion, _In_ const OrtGraph* graph, _Out_ int64_t* onnx_ir_version);
+
+ /** \brief Returns the number of operator sets that the graph's model uses.
+ *
+ * \note An operator set is uniquely identified by the (domain, opset_version) pair. All models must have at
+ * least one entry that specifies which entry of the ONNX operator set is used. The ONNX domain is represented by
+ * an empty string.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] num_operator_sets Output parameter set to the number of operator sets that the graph's model uses.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNumOperatorSets, _In_ const OrtGraph* graph, _Out_ size_t* num_operator_sets);
+
+ /** \brief Returns the operator sets that the graph's model uses.
+ *
+ * \note An operator set is uniquely identified by the (domain, opset_version) pair. All models must have at
+ * least one entry that specifies which entry of the ONNX operator set is used. The ONNX domain is represented by
+ * an empty string.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] domains Pre-allocated array of `num_operator_sets` elements that is filled with
+ * null-terminated domain names.
+ * \param[out] opset_versions Pre-allocated array of `num_operator_sets` elements that is filled with
+ * the opset version of the corresponding domain in the `domains` array.
+ * \param[in] num_operator_sets The size of the `domains` and `opset_versions` arrays.
+ * Typical usage sets this to the result of Graph_GetNumOperatorSets().
+ * An error status is returned if `num_operator_sets` is less than the actual number
+ * of operator sets.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetOperatorSets, _In_ const OrtGraph* graph,
+ _Out_writes_(num_operator_sets) const char** domains,
+ _Out_writes_(num_operator_sets) int64_t* opset_versions, _In_ size_t num_operator_sets);
+
+ /** \brief Returns the number of graph inputs.
+ *
+ * \note The count includes initializers that are included in the list of graph inputs.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] num_inputs Output parameter set to the number of graph inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNumInputs, _In_ const OrtGraph* graph, _Out_ size_t* num_inputs);
+
+ /** \brief Returns the graph's inputs as OrtValueInfo instances.
+ *
+ * \note The result includes initializers that are included in the list of graph inputs.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] inputs Pre-allocated array of `num_inputs` elements that is filled with the graph's inputs.
+ * \param[in] num_inputs The size of the `inputs` array.
+ * Typical usage sets this to the result of Graph_GetNumInputs(). An error status is
+ * returned if `num_inputs` is less than the number of graph inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetInputs, _In_ const OrtGraph* graph,
+ _Out_writes_(num_inputs) const OrtValueInfo** inputs, _In_ size_t num_inputs);
+
+ /** \brief Returns the number of graph outputs.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] num_outputs Output parameter set to the number of graph outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNumOutputs, _In_ const OrtGraph* graph, _Out_ size_t* num_outputs);
+
+ /** \brief Returns the graph's outputs as OrtValueInfo instances.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] outputs Pre-allocated array of `num_outputs` elements that is filled with the graph's outputs.
+ * \param[in] num_outputs The size of the `outputs` array.
+ * Typical usage sets this to the result of Graph_GetNumOutputs(). An error status is
+ * returned if `num_outputs` is less than the number of graph outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetOutputs, _In_ const OrtGraph* graph,
+ _Out_writes_(num_outputs) const OrtValueInfo** outputs, _In_ size_t num_outputs);
+
+ /** \brief Returns the number of graph initializers.
+ *
+ * Counts constant and non-constant initializers.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] num_initializers Output parameter set to the number of graph initializers.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNumInitializers, _In_ const OrtGraph* graph, _Out_ size_t* num_initializers);
+
+ /** \brief Returns the graph's initializers as OrtValueInfo instances.
+ *
+ * Includes constant and non-constant initializers.
+ *
+ * For ONNX IR version < 4, all initializers are constant.
+ *
+ * For ONNX IR version >= 4, an initializer with a name that matches a graph input is considered a
+ * non-constant initializer.
+ *
+ * Call ValueInfo_GetInitializerValue to get the initializer's data.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] initializers Pre-allocated array of `num_outputs` elements that is filled with the initializers.
+ * \param[in] num_initializers The size of the `initializers` array. Typical usage sets this to the
+ * result of Graph_GetNumInitializers(). An error status is returned if
+ * `num_initializers` is less than the number of graph initializers.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetInitializers, _In_ const OrtGraph* graph,
+ _Out_writes_(num_initializers) const OrtValueInfo** initializers,
+ _In_ size_t num_initializers);
+
+ /** \brief Returns the number of graph nodes.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] num_nodes Output parameter set to the number of graph nodes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNumNodes, _In_ const OrtGraph* graph, _Out_ size_t* num_nodes);
+
+ /** \brief Returns the graph's nodes as OrtNode instances.
+ *
+ * The nodes are sorted using a stable topological ordering. Callers are responsible for maintaining their
+ * own node ordering if a different order is required.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] nodes Pre-allocated array of `num_nodes` elements that is filled with the graph's nodes.
+ * \param[in] num_nodes The size of the `nodes` array. Typical usage sets this to the
+ * result of Graph_GetNumNodes(). An error status is returned if
+ * `num_nodes` is less than the number of graph nodes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetNodes, _In_ const OrtGraph* graph,
+ _Out_writes_(num_nodes) const OrtNode** nodes, _In_ size_t num_nodes);
+
+ /** \brief Get the parent node for the given graph, if any exists.
+ *
+ * Certain operator types (e.g., If and Loop) contain nested subgraphs. This function enables
+ * access to the parent node (e.g., the If and Loop node) from a nested subgraph.
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] node Output parameter that is set to the graph's parent node.
+ * Set to NULL if a parent node does not exist (e.g., for a top-level graph).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetParentNode, _In_ const OrtGraph* graph, _Outptr_result_maybenull_ const OrtNode** node);
+
+ /** \brief Returns an OrtGraph that contains a subset of nodes in the source OrtGraph.
+ *
+ * \note The lifetime of "dst_graph" is tied to that of "src_graph", as they both internally reference
+ * the same underlying graph. "dst_graph" preserves the input order of "src_graph", and
+ * its output order corresponds to the outputs produced by the nodes in "nodes" with the given order.
+ *
+ * \param[in] src_graph The source OrtGraph instance.
+ * \param[in] nodes A subset of the nodes/OrtNodes in 'graph'.
+ * \param[in] num_nodes Number of nodes.
+ * \param[out] dst_graph An OrtGraph created from a given set of nodes. Must be released by calling ReleaseGraph.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetGraphView, _In_ const OrtGraph* src_graph, _In_ const OrtNode** nodes,
+ _In_ size_t num_nodes, _Outptr_ OrtGraph** dst_graph);
+
+ /// @}
+
+ /// \name OrtNode
+ /// @{
+
+ /** \brief Returns a node's identifier.
+ *
+ * The node's identifier is only unique in the node's parent graph. Different nested subgraphs
+ * (e.g., subgraphs contained by If and Loop nodes) may reuse identifiers.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] node_id Output parameter set to the node's identifier.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetId, _In_ const OrtNode* node, _Out_ size_t* node_id);
+
+ /** \brief Returns a node's name. Can be an empty string.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] node_name Output parameter set to the node's name.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetName, _In_ const OrtNode* node, _Outptr_ const char** node_name);
+
+ /** \brief Returns a node's operator type (e.g., "Conv").
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] operator_type Output parameter set to the name of the node's operator type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetOperatorType, _In_ const OrtNode* node, _Outptr_ const char** operator_type);
+
+ /** \brief Returns a node's domain name.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] domain_name Output parameter set to the node's domain name.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetDomain, _In_ const OrtNode* node, _Outptr_ const char** domain_name);
+
+ /** \brief Get the opset version in which the given node's operator type was first defined.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] since_version The opset version in which the node's operator type was first defined.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetSinceVersion, _In_ const OrtNode* node, _Out_ int* since_version);
+
+ /** \brief Returns the number of node inputs.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] num_inputs Output parameter set to the number of node inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetNumInputs, _In_ const OrtNode* node, _Out_ size_t* num_inputs);
+
+ /** \brief Returns the node's inputs as OrtValueInfo instances.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] inputs Pre-allocated array of `num_inputs` elements that is filled with the node's inputs.
+ * \param[in] num_inputs The size of the `inputs` array.
+ * Typical usage sets this to the result of Node_GetNumInputs(). An error status is
+ * returned if `num_inputs` is less than the number of node inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetInputs, _In_ const OrtNode* node,
+ _Out_writes_(num_inputs) const OrtValueInfo** inputs, _In_ size_t num_inputs);
+
+ /** \brief Returns the number of node outputs.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] num_outputs Output parameter set to the number of node outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetNumOutputs, _In_ const OrtNode* node, _Out_ size_t* num_outputs);
+
+ /** \brief Returns the node's outputs as OrtValueInfo instances.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] outputs Pre-allocated array of `num_outputs` elements that is filled with the node's outputs.
+ * \param[in] num_outputs The size of the `outputs` array.
+ * Typical usage sets this to the result of Node_GetNumOutputs(). An error status is
+ * returned if `num_outputs` is less than the number of node outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetOutputs, _In_ const OrtNode* node,
+ _Out_writes_(num_outputs) const OrtValueInfo** outputs, _In_ size_t num_outputs);
+
+ /** \brief Returns the number of node implicit inputs.
+ *
+ * Certain operator types (e.g., If and Loop) contain nested subgraphs. The internal nodes within the nested subgraphs
+ * may use values from the outer scope. Those "outer scope" values are considered implicit inputs to the node that
+ * contains the subgraphs (e.g., the If or Loop node).
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] num_implicit_inputs Output parameter set to the number of node implicit inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetNumImplicitInputs, _In_ const OrtNode* node, _Out_ size_t* num_implicit_inputs);
+
+ /** \brief Get the implicit inputs, as OrtValueInfo instances, that are used within the given node's subgraphs.
+ *
+ * \note Only certain operator types (e.g., If and Loop) contain nested subgraphs.
+ * The internal nodes within the nested subgraphs may use values from the outer scope. Those "outer scope" values
+ * are considered implicit inputs to the node that contains the subgraphs (e.g., the If or Loop node).
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] implicit_inputs Pre-allocated array of `num_implicit_inputs` elements that is filled the node's
+ * implicit inputs.
+ * \param[in] num_implicit_inputs The size of the `implicit_inputs` array. Typical usage sets this to the result
+ * of Node_GetNumImplicitInputs(). An error status is returned if
+ * `num_implicit_inputs` is less than the number of node implicit inputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetImplicitInputs, _In_ const OrtNode* node,
+ _Out_writes_(num_implicit_inputs) const OrtValueInfo** implicit_inputs,
+ _In_ size_t num_implicit_inputs);
+
+ /** \brief Returns the number of node attributes.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] num_attributes Output parameter set to the number of node attributes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetNumAttributes, _In_ const OrtNode* node, _Out_ size_t* num_attributes);
+
+ /** \brief Returns a node's attributes as OrtOpAttr instances.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] attributes Pre-allocated array of `num_attributes` elements that is filled with the node's attributes.
+ * \param[in] num_attributes The size of the `num_attributes` array.
+ * Typical usage sets this to the result of Node_GetNumAttributes(). An error status is
+ * returned if `num_attributes` is less than the number of node attributes.
+ *
+ * \note ONNX Runtime automatically sets optional (unset) attributes to their default values if the default value
+ * is a constant expression that does not depend on other tensor/model characteristics. Conv's 'kernel_shape'
+ * attribute is an example of an optional attribute that does not have a constant default value. This function
+ * does not provide any unset optional attributes without a constant default value.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetAttributes, _In_ const OrtNode* node,
+ _Out_writes_(num_attributes) const OrtOpAttr** attributes, _In_ size_t num_attributes);
+
+ /** \brief Gets the OrtNode's attribute as OrtOpAttr by name.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[in] attribute_name The name of the attribute
+ * \param[out] attribute Output parameter set to the OrtOpAttr instance if an attribute by the given name exists.
+ * For an unset optional attribute, `attribute` is set to NULL and a non-error status is
+ * returned. For an invalid attribute name, `attribute` is set to NULL and an error status with
+ * code ORT_NOT_FOUND is returned.
+ *
+ * \note ONNX Runtime automatically sets optional (unset) attributes to their default values if the default value
+ * is a constant expression that does not depend on other tensor/model characteristics. Conv's 'kernel_shape'
+ * attribute is an example of an optional attribute that does not have a constant default value. This function
+ * does not provide any unset optional attributes without a constant default value.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetAttributeByName, _In_ const OrtNode* node, _In_ const char* attribute_name,
+ _Outptr_result_maybenull_ const OrtOpAttr** attribute);
+
+ /** \brief Get the OrtNode's 'TENSOR' attribute as an OrtValue.
+ *
+ * \param[in] attribute The OrtOpAttr instance.
+ * \param[out] attr_tensor If successful, contains the 'TENSOR' attribute as a newly created OrtValue.
+ Must be freed with OrtApi::ReleaseValue.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OpAttr_GetTensorAttributeAsOrtValue, _In_ const OrtOpAttr* attribute,
+ _Outptr_result_maybenull_ OrtValue** attr_tensor);
+
+ /** \brief Get the attribute type as OrtOpAttrType from an OrtOpAttr.
+ *
+ * \param[in] attribute The OrtOpAttr instance.
+ * \param[out] type Output the attribute type as OrtOpAttrType.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OpAttr_GetType, _In_ const OrtOpAttr* attribute, _Out_ OrtOpAttrType* type);
+
+ /** \brief Get the attribute name from an OrtOpAttr.
+ *
+ * \param[in] attribute The OrtOpAttr instance.
+ * \param[out] name Output parameter set to the attribute's name. The name is a null-terminated string.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OpAttr_GetName, _In_ const OrtOpAttr* attribute, _Outptr_ const char** name);
+
+ /** \brief Returns the number of subgraphs contained by the given node.
+ *
+ * \note Only certain operator types (e.g., If and Loop) contain nested subgraphs.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] num_subgraphs Output parameter set to the number of node subgraphs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetNumSubgraphs, _In_ const OrtNode* node, _Out_ size_t* num_subgraphs);
+
+ /** \brief Get the subgraphs, as OrtGraph instances, contained by the given node.
+ *
+ * \note Only certain operator types (e.g., If and Loop) contain nested subgraphs. ONNX nodes store subgraphs in
+ * their attributes, however, this function must be used to obtain subgraphs from an OrtNode.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] subgraphs Pre-allocated array of `num_subgraphs` elements that is filled with the node's subgraphs.
+ * \param[in] num_subgraphs The size of the `num_subgraphs` array.
+ * Typical usage sets this to the result of Node_GetNumSubgraphs(). An error status is
+ * returned if `num_subgraphs` is less than the number of node subgraphs.
+ * \param[out] attribute_names Optional pre-allocated array of `num_subgraphs` elements that is filled with the
+ * attribute names that correspond to the subgraphs. Ignored if set to NULL.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetSubgraphs, _In_ const OrtNode* node,
+ _Out_writes_(num_subgraphs) const OrtGraph** subgraphs, _In_ size_t num_subgraphs,
+ _Out_writes_opt_(num_subgraphs) const char** attribute_names);
+
+ /** \brief Get the node's parent OrtGraph instance.
+ *
+ * Can return NULL if the OrtNode was created without an owning graph.
+ * In another case, this API may also return NULL if `node` is obtained by calling Graph_GetParentNode()
+ * on an OrtGraph that is a subgraph of a control-flow op, and the parent graph has not been created yet,
+ * for example during ORT's GetCapability() when processing the innermost subgraph.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] graph Output parameter set to the node's OrtGraph. Can be set to NULL
+ * if the node is not currently contained by a graph.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetGraph, _In_ const OrtNode* node, _Outptr_result_maybenull_ const OrtGraph** graph);
+
+ /** \brief Returns the execution provider name that this node is assigned to run on.
+ * Returns NULL if the node has not been assigned to any execution provider yet.
+ * For plugin execution providers, the name is the one returned by OrtEp::GetName.
+ *
+ * \param[in] node The OrtNode instance.
+ * \param[out] out Output execution provider type and can be NULL if node has not been assigned.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Node_GetEpName, _In_ const OrtNode* node, _Outptr_result_maybenull_ const char** out);
+
+ /// @}
+
+ /// \name OrtExternalInitializerInfo
+ /// @{
+
+ /** \brief Release an OrtExternalInitializerInfo instance.
+ *
+ * \param[in] input OrtExternalInitializerInfo instance to be released.
+ *
+ * \since Version 1.23.
+ */
+ ORT_CLASS_RELEASE(ExternalInitializerInfo);
+
+ /** \brief Get the relative path to the file that stores the initializer's data.
+ *
+ * \note The path is relative to the filesystem directory where the ONNX model was stored.
+ * Caller can use Graph_GetModelPath to get the model's full path and construct the absolute path to the
+ * external initializer file if necessary.
+ *
+ * \param[in] info The OrtExternalInitializerInfo instance.
+ * \return The relative path to the file that stores the initializer's data. Do NOT free this pointer.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const ORTCHAR_T*, ExternalInitializerInfo_GetFilePath, _In_ const OrtExternalInitializerInfo* info);
+
+ /** \brief Get the byte offset within the file where the initializer's data is stored.
+ *
+ * \param[in] info The OrtExternalInitializerInfo instance.
+ * \return The byte offset where the initializer's data is stored within the file.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(int64_t, ExternalInitializerInfo_GetFileOffset, _In_ const OrtExternalInitializerInfo* info);
+
+ /** \brief Get the size in bytes of the initializer's data within the file.
+ *
+ * \param[in] info The OrtExternalInitializerInfo instance.
+ * \return The size in bytes of the initializer's data within the file.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(size_t, ExternalInitializerInfo_GetByteSize, _In_ const OrtExternalInitializerInfo* info);
+
+ /// @}
+
+ /// \name OrtRunOptions
+ /// @{
+
+ /** \brief Get a run configuration entry.
+ *
+ * If a run configuration entry with key `config_key` doesn't exist, `config_value` will be set to NULL.
+ *
+ * `config_key`s are defined in onnxruntime_run_options_config_keys.h.
+ *
+ * \param[in] options The OrtRunOptions instance.
+ * \param[in] config_key The configuration entry key. A null-terminated string.
+ * \return The configuration entry value. Either a null-terminated string if the entry was found. nullptr otherwise.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API_T(const char*, GetRunConfigEntry, _In_ const OrtRunOptions* options,
+ _In_z_ const char* config_key);
+
+ /// @}
+
+ /** \brief Get the OrtMemoryInfo for the device.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to query.
+ * \param[in] memory_type The memory type to return.
+ * \return A pointer to the OrtMemoryInfo for the device. This may be nullptr if not set.
+ * If memory_type is OrtDeviceMemoryType_DEFAULT and nullptr is returned the EP uses CPU memory.
+ *
+ * \since Version 1.23
+ */
+ ORT_API_T(const OrtMemoryInfo*, EpDevice_MemoryInfo, _In_ const OrtEpDevice* ep_device,
+ _In_ OrtDeviceMemoryType memory_type);
+
+ /** \brief Create/replace a shared allocator for the OrtEpDevice in the OrtEnv.
+ *
+ * OrtEpDevice maps to the EP factory, and the factory provides the allocator implementation.
+ *
+ * Both OrtDeviceMemoryType_DEFAULT and OrtDeviceMemoryType_HOST_ACCESSIBLE are optional for an EP to provide.
+ * It is EP implementation dependent as to what is available.
+ *
+ * If a shared allocator already exists for the OrtEpDevice and OrtDeviceMemoryType, it is replaced. This allows
+ * changing the shared allocator configuration from the default. e.g. adding an arena.
+ *
+ * \param[in] env The OrtEnv instance to create the shared allocator in.
+ * \param[in] ep_device The OrtEpDevice instance to create the shared allocator for.
+ * \param[in] mem_type The memory type to use for the shared allocator.
+ * \param[in] allocator_type The type of allocator to create. Only OrtDeviceAllocator is valid currently.
+ * \param[in] allocator_options Optional key-value pairs to configure the allocator. If arena based, see
+ * include/onnxruntime/core/framework/allocator.h for the keys and values that can be
+ * used.
+ * \param[out] allocator A pointer to the created shared allocator. Owned by the OrtEnv instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(CreateSharedAllocator, _In_ OrtEnv* env, _In_ const OrtEpDevice* ep_device,
+ _In_ OrtDeviceMemoryType mem_type, _In_ OrtAllocatorType allocator_type,
+ _In_opt_ const OrtKeyValuePairs* allocator_options,
+ _Outptr_opt_ OrtAllocator** allocator);
+
+ /** \brief Get a shared allocator from the OrtEnv.
+ *
+ * By default there is a shared allocator created for all OrtEpDevice instances, so if you get the OrtMemoryInfo
+ * from the OrtEpDevice using EpDevice_MemoryInfo a shared allocator is guaranteed to exist.
+ *
+ * This will also match and return custom allocators added with RegisterAllocator.
+ *
+ * It is not an error to not find a matching allocator.
+ *
+ * \param[in] env The OrtEnv instance to get the shared allocator from.
+ * \param[in] mem_info The OrtMemoryInfo instance to get the shared allocator for.
+ * \param[out] allocator A pointer to the shared allocator, or nullptr if no shared allocator exists for
+ * the given memory info.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(GetSharedAllocator, _In_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info,
+ _Outptr_result_maybenull_ OrtAllocator** allocator);
+
+ /** \brief Release a shared allocator from the OrtEnv for the OrtEpDevice and memory type.
+ *
+ * This will release the shared allocator for the given OrtEpDevice and memory type.
+ * If no shared allocator exists, this is a no-op.
+ *
+ * \param[in] env The OrtEnv instance to release the shared allocator from.
+ * \param[in] ep_device The OrtEpDevice instance to release the shared allocator for.
+ * \param[in] mem_type The memory type of the shared allocator to release.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(ReleaseSharedAllocator, _In_ OrtEnv* env, _In_ const OrtEpDevice* ep_device,
+ _In_ OrtDeviceMemoryType mem_type);
+
+ /** \brief Get a const pointer to the raw data inside a tensor
+ *
+ * Used to read the internal tensor data directly.
+ * \note The returned pointer is valid until the OrtValue is destroyed.
+ *
+ * \param[in] value A tensor type (string tensors are not supported)
+ * \param[out] out Filled in with a pointer to the internal storage
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(GetTensorData, _In_ const OrtValue* value, _Outptr_ const void** out);
+
+ /** \brief Get Session configuration entries.
+ *
+ * \param[in] options The session options.
+ * \param[out] out A pointer to a newly created OrtKeyValuePairs instance.
+ *
+ * An OrtKeyValuePairs instance containing all session configuration entries.
+ * Note: the user should call OrtApi::ReleaseKeyValuePairs.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(GetSessionOptionsConfigEntries, _In_ const OrtSessionOptions* options, _Outptr_ OrtKeyValuePairs** out);
+
+ /** \brief Get the OrtMemoryInfo for each input of the session.
+ *
+ * The memory info can be used to determine where the input tensors are required.
+ *
+ * The session must be fully initialized before calling this function as the input locations are not known until
+ * this has occurred.
+ *
+ * \param[in] session The OrtSession instance.
+ * \param[out] inputs_memory_info Pre-allocated array of size `num_inputs` that will be filled with the
+ * OrtMemoryInfo* value for each input.
+ * The order is the same as returned by SessionGetInputName.
+ * \param[in] num_inputs The number of inputs in the session. Must match SessionGetInputCount.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(SessionGetMemoryInfoForInputs, _In_ const OrtSession* session,
+ _Out_writes_(num_inputs) const OrtMemoryInfo** inputs_memory_info,
+ _In_ size_t num_inputs);
+
+ /** \brief Get the OrtMemoryInfo for each output of the session.
+ *
+ * The memory info can be used to determine the device the output tensors are produced on.
+ * The user can pre-allocate an OrtValue using this information or use IOBinding to keep the data on the device.
+ * ORT will copy the output to CPU otherwise.
+ *
+ * The session must be fully initialized before calling this function as the output locations are not known until
+ * this has occurred.
+ *
+ * \param[in] session The OrtSession instance.
+ * \param[out] outputs_memory_info Pre-allocated array of size `num_outputs` that will be filled with
+ * OrtMemoryInfo* values for each output.
+ * The order is the same as returned by SessionGetOutputName.
+ * \param[in] num_outputs The number of outputs in the session. Must match SessionGetOutputCount.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(SessionGetMemoryInfoForOutputs, _In_ const OrtSession* session,
+ _Out_writes_(num_outputs) const OrtMemoryInfo** outputs_memory_info,
+ _In_ size_t num_outputs);
+
+ /** \brief Get the OrtEpDevice (if available) for each input of the session.
+ *
+ * An OrtEpDevice will be available if auto EP selection is enabled by calling
+ * SessionOptionsSetEpSelectionPolicy or SessionOptionsSetEpSelectionPolicyDelegate,
+ * or if the OrtEpDevice was manually added to the session using SessionOptionsAppendExecutionProvider_V2.
+ *
+ * If an OrtEpDevice is not available for the input a nullptr is returned.
+ *
+ * The returned OrtEpDevice can be used to create an OrtSyncStream via CreateSyncStreamForEpDevice to asynchronously
+ * provide input to the inference session Run.
+ *
+ * The session must be fully initialized before calling this function as the assigned EPs are not known until
+ * this has occurred.
+ *
+ * \param[in] session The OrtSession instance.
+ * \param[out] inputs_ep_devices Pre-allocated array of size `num_inputs` that will be filled with
+ * OrtEpDevice* values for each input.
+ * The order is the same as returned by SessionGetInputName.
+ * \param[in] num_inputs The number of inputs in the session. Must match SessionGetInputCount.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(SessionGetEpDeviceForInputs, _In_ const OrtSession* session,
+ _Out_writes_(num_inputs) const OrtEpDevice** inputs_ep_devices,
+ _In_ size_t num_inputs);
+
+ /** \brief Create an OrtSyncStream for the given OrtEpDevice.
+ *
+ * The OrtSyncStream can be used to enable asynchronous operations.
+ * e.g. async usage of CopyTensors to provide input to an OrtSession Run call.
+ *
+ * An error code of ORT_NOT_IMPLEMENTED will be returned if the EP does not support OrtSyncStream.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to create the sync stream for.
+ * \param[in] stream_options Options for OrtSyncStream creation. May be nullptr.
+ * \param[out] stream Output parameter set to the created OrtSyncStream instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(CreateSyncStreamForEpDevice, _In_ const OrtEpDevice* ep_device,
+ _In_opt_ const OrtKeyValuePairs* stream_options,
+ _Outptr_ OrtSyncStream** stream);
+
+ /** \brief Get the native handle of the sync stream.
+ *
+ * This returns the native handle for the stream. e.g. cudaStream_t for CUDA streams.
+ *
+ * \param[in] stream The OrtSyncStream instance to get the handle from.
+ *
+ * \returns The native handle of the stream.
+ *
+ * \since Version 1.23
+ */
+ ORT_API_T(void*, SyncStream_GetHandle, _In_ OrtSyncStream* stream);
+
+ ORT_CLASS_RELEASE(SyncStream);
+
+ /** \brief Copy OrtValue instances containing Tensors between devices.
+ *
+ * The overall copy must be between a single source device and a single destination device. i.e.
+ * - all src_tensors must have matching OrtMemoryInfo,
+ * - all dst_tensors must have matching OrtMemoryInfo.
+ *
+ * OrtValue instances can be created by:
+ * - Use GetSharedAllocator to get the shared allocator for the OrtMemoryInfo if you need to allocate memory
+ * on the device.
+ * - Use CreateTensorAsOrtValue, CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue
+ * to create an OrtValue containing a tensor depending on whether you have existing data or not, and whether
+ * you want ORT to free the existing data once it is done with the OrtValue.
+ *
+ * \param[in] env The OrtEnv instance to use. The data transfer implementation is provided by an execution provider
+ * that is registered in this OrtEnv.
+ * \param[in] src_tensors Array of OrtValue instances containing the source tensors to copy.
+ * \param[in] dst_tensors Array of OrtValue instances to copy the source tensors to.
+ * \param[in] stream Optional OrtSyncStream that can be used to perform the copy asynchronously. May be nullptr.
+ * \param[in] num_tensors The number of tensors to copy. The size of `src_tensors` and `dst_tensors` must match.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23
+ */
+ ORT_API2_STATUS(CopyTensors, _In_ const OrtEnv* env,
+ _In_reads_(num_tensors) const OrtValue* const* src_tensors,
+ _In_reads_(num_tensors) OrtValue* const* dst_tensors,
+ _In_opt_ OrtSyncStream* stream,
+ _In_ size_t num_tensors);
+
+ /** \brief Get ::OrtModelMetadata from an ::OrtGraph
+ *
+ * \param[in] graph The OrtGraph instance.
+ * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Graph_GetModelMetadata, _In_ const OrtGraph* graph, _Outptr_ OrtModelMetadata** out);
+
+ /** \brief Validate a compiled model's compatibility information for one or more EP devices.
+ *
+ * \param[in] ep_devices The EP devices to validate against (e.g., from GetEpDevices).
+ * All devices must belong to the same execution provider.
+ * \param[in] num_ep_devices The number of EP devices provided.
+ * \param[in] compatibility_info The compatibility info string produced when the model was compiled.
+ * \param[out] out_status The resulting compatibility status for the EP devices.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(GetModelCompatibilityForEpDevices,
+ _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices,
+ _In_ size_t num_ep_devices,
+ _In_ const char* compatibility_info,
+ _Out_ OrtCompiledModelCompatibility* out_status);
+
+ /// \name OrtExternalInitializerInfo
+ /// @{
+
+ /** \brief Creates an OrtExternalInitializerInfo instance.
+ *
+ * \param[in] filepath The relative path to the file that stores the initializer's data. ORT copies this path string.
+ * \param[in] file_offset The byte offset where the initializer's data is stored within the file.
+ * \param[in] byte_size The size in bytes of the initializer's data within the file.
+ * \param[out] out Output parameter set to the new OrtExternalInitializerInfo instance.
+ * Must be released by calling ReleaseExternalInitializerInfo().
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateExternalInitializerInfo, _In_ const ORTCHAR_T* filepath, _In_ int64_t file_offset,
+ _In_ size_t byte_size, _Outptr_ OrtExternalInitializerInfo** out);
+
+ /// @}
+ /** \brief Fetch whether the tensor has shape information.
+ * \param[in] info The OrtTensorTypeAndShapeInfo instance.
+ * \return true if the tensor has shape information, false otherwise.
+ *
+ * \since Version 1.24
+ */
+ ORT_API_T(bool, TensorTypeAndShape_HasShape, _In_ const OrtTensorTypeAndShapeInfo* info);
+
+ /** \brief Get all config entries from ::OrtKernelInfo.
+ *
+ * Gets all configuration entries from the ::OrtKernelInfo object as key-value pairs.
+ * Config entries are set on the ::OrtSessionOptions and are accessible in custom operator kernels.
+ *
+ * Used in the CreateKernel callback of an OrtCustomOp to access all session configuration entries
+ * during kernel construction.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] out A pointer to a newly created OrtKeyValuePairs instance containing all config entries.
+ * Note: the user should call OrtApi::ReleaseKeyValuePairs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(KernelInfo_GetConfigEntries, _In_ const OrtKernelInfo* info, _Outptr_ OrtKeyValuePairs** out);
+
+ /** \brief Get the graph node's operator domain from ::OrtKernelInfo.
+ *
+ * If `out` is nullptr, the value of `size` is set to the size of the operator domain
+ * string (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the string's size and `out` is not nullptr,
+ * the value of `size` is set to the true size of the string (including null-terminator),
+ * the provided memory is filled with the string's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string
+ * and a failure status with error code ORT_INVALID_ARGUMENT is returned.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the
+ * operator domain.
+ * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(KernelInfo_GetOperatorDomain, _In_ const OrtKernelInfo* info, _Out_opt_ char* out,
+ _Inout_ size_t* size);
+
+ /** \brief Get the graph node's operator type from ::OrtKernelInfo.
+ *
+ * If `out` is nullptr, the value of `size` is set to the size of the operator type
+ * string (including null-terminator), and a success status is returned.
+ *
+ * If the `size` parameter is greater than or equal to the string's size and `out` is not nullptr,
+ * the value of `size` is set to the true size of the string (including null-terminator),
+ * the provided memory is filled with the string's contents, and a success status is returned.
+ *
+ * If the `size` parameter is less than the actual string's size and `out`
+ * is not nullptr, the value of `size` is set to the true size of the string
+ * and a failure status with error code ORT_INVALID_ARGUMENT is returned.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the
+ * operator type.
+ * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(KernelInfo_GetOperatorType, _In_ const OrtKernelInfo* info, _Out_opt_ char* out,
+ _Inout_ size_t* size);
+
+ /** \brief Get the opset version in which the given node's operator type was first defined from ::OrtKernelInfo.
+ *
+ * \param[in] info An instance of ::OrtKernelInfo.
+ * \param[out] since_version The opset version in which the node's operator type was first defined.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(KernelInfo_GetOperatorSinceVersion, _In_ const OrtKernelInfo* info,
+ _Out_ int* since_version);
+
+ /** \brief Get the EP Interop API instance.
+ *
+ * Get the Interop API instance to work with external resources. This API provides functions
+ * for importing external GPU memory and semaphores for zero-copy sharing between ORT inference
+ * and other GPU workloads.
+ *
+ * \return Interop API struct instance.
+ *
+ * \since Version 1.24.
+ */
+ const OrtInteropApi*(ORT_API_CALL* GetInteropApi)(void);
+
+ /** \brief Get the EP device assigned to each session output.
+ *
+ * Returns the OrtEpDevice assigned to each output of the session after graph partitioning.
+ * This allows validation that outputs are placed on the expected device for external resource sharing.
+ *
+ * The EP device for each output is determined by which execution provider will produce that output
+ * during inferencing. This information is useful for:
+ * - Validating that outputs will be placed on the expected device for external resource sharing
+ * - Deciding whether to use external memory handles for outputs
+ *
+ * \param[in] session The OrtSession instance to query.
+ * \param[out] outputs_ep_devices An array to be filled with the EP device for each output.
+ * The array must be allocated by the caller with space for
+ * OrtEpDevice* values for each output.
+ * The order is the same as returned by SessionGetOutputName.
+ * \param[in] num_outputs The number of outputs in the session. Must match SessionGetOutputCount.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(SessionGetEpDeviceForOutputs, _In_ const OrtSession* session,
+ _Out_writes_(num_outputs) const OrtEpDevice** outputs_ep_devices,
+ _In_ size_t num_outputs);
+ /** \brief Get the number of available hardware devices.
+ *
+ * Returns the count of hardware devices discovered on the system.
+ * Use this to allocate an array before calling GetHardwareDevices().
+ *
+ * \param[in] env The OrtEnv instance where device discovery results are stored.
+ * \param[out] num_devices The number of OrtHardwareDevice instances available.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetNumHardwareDevices, _In_ const OrtEnv* env, _Out_ size_t* num_devices);
+
+ /** \brief Get the list of available hardware devices.
+ *
+ * Enumerates hardware devices available on the system.
+ * Populates a user-provided array with pointers to OrtHardwareDevice instances. The caller is responsible
+ * for allocating the array with sufficient space (use GetNumHardwareDevices() to get the count).
+ *
+ * The returned pointers reference internal ORT data structures that are discovered once at process
+ * startup and remain valid for the lifetime of the OrtEnv. The caller does not need to release these
+ * pointers, but should not use them after calling ReleaseEnv().
+ *
+ * \param[in] env The OrtEnv instance where device discovery results are stored.
+ * \param[out] devices User-allocated array to receive pointers to OrtHardwareDevice instances.
+ * The array must have space for at least num_devices elements.
+ * \param[in] num_devices The size of the user-allocated devices array.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetHardwareDevices, _In_ const OrtEnv* env,
+ _Out_writes_(num_devices) const OrtHardwareDevice** devices,
+ _In_ size_t num_devices);
+
+ /** \brief Check for known incompatibility issues between hardware device and a specific execution provider.
+ *
+ * This function checks for known incompatibility issues between the specified hardware device
+ * and a specific execution provider.
+ * If returned incompatibility details have non-zero reasons, it indicates the device is not compatible.
+ * However, if returned detail have reason == 0, it doesn't guarantee 100% compatibility for all models,
+ * as models may have specific requirements.
+ *
+ * Note: This method should only be called when the OrtEnv has been initialized with execution
+ * providers (after RegisterExecutionProviderLibrary is called).
+ *
+ * \param[in] env The OrtEnv instance with registered execution providers.
+ * \param[in] ep_name The name of the execution provider to check. Required and cannot be null or empty.
+ * \param[in] hw The hardware device to check for incompatibility.
+ * \param[out] details Compatibility details including reasons for incompatibility if any.
+ * Must be freed with OrtApi::ReleaseDeviceEpIncompatibilityDetails.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetHardwareDeviceEpIncompatibilityDetails, _In_ const OrtEnv* env,
+ _In_ const char* ep_name,
+ _In_ const OrtHardwareDevice* hw,
+ _Outptr_ OrtDeviceEpIncompatibilityDetails** details);
+
+ /// \name OrtDeviceEpIncompatibilityDetails
+ /// Accessor functions for device incompatibility details
+ /// @{
+
+ /** \brief Get the incompatibility reasons bitmask from OrtDeviceEpIncompatibilityDetails.
+ *
+ * \param[in] details The OrtDeviceEpIncompatibilityDetails instance to query.
+ * \param[out] reasons_bitmask Pointer to store the bitmask of incompatibility reasons.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(DeviceEpIncompatibilityDetails_GetReasonsBitmask,
+ _In_ const OrtDeviceEpIncompatibilityDetails* details,
+ _Out_ uint32_t* reasons_bitmask);
+
+ /** \brief Get the notes from OrtDeviceEpIncompatibilityDetails.
+ *
+ * \param[in] details The OrtDeviceEpIncompatibilityDetails instance to query.
+ * \param[out] notes Pointer to the notes string. May be nullptr if no notes are available.
+ * The returned string is owned by the details object and should not be freed.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(DeviceEpIncompatibilityDetails_GetNotes,
+ _In_ const OrtDeviceEpIncompatibilityDetails* details,
+ _Outptr_result_maybenull_ const char** notes);
+
+ /** \brief Get the execution provider error code from OrtDeviceEpIncompatibilityDetails.
+ *
+ * This allows Independent Hardware Vendors (IHVs) to define their own error codes
+ * to provide additional details about device incompatibility.
+ *
+ * \param[in] details The OrtDeviceEpIncompatibilityDetails instance to query.
+ * \param[out] error_code Pointer to store the EP-specific error code. A value of 0 indicates no error code was set.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(DeviceEpIncompatibilityDetails_GetErrorCode,
+ _In_ const OrtDeviceEpIncompatibilityDetails* details,
+ _Out_ int32_t* error_code);
+
+ /** \brief Release an OrtDeviceEpIncompatibilityDetails instance.
+ *
+ * \since Version 1.24.
+ */
+ ORT_CLASS_RELEASE(DeviceEpIncompatibilityDetails);
+
+ /// @}
+
+ /// \name Model Compatibility APIs
+ /// @{
+
+ /** \brief Extract EP compatibility info from a precompiled model file.
+ *
+ * Parses the model file to extract the compatibility info string for a specific execution provider
+ * from the model's metadata properties. This is only applicable to models that have been precompiled
+ * for an EP (e.g., via OrtCompileApi). Standard ONNX models do not contain this information.
+ *
+ * The compatibility info string must be valid UTF-8 without embedded NUL characters.
+ *
+ * \note This API performs standalone model parsing, separate from session creation. This means
+ * the protobuf parsing cost is incurred here and again during session creation. It is intended
+ * for scenarios where applications need to check compatibility before deciding whether to proceed
+ * with session creation, such as providing early user feedback.
+ *
+ * \note This operation parses the full ONNX ModelProto from disk. For very large models, consider
+ * using GetCompatibilityInfoFromModelBytes with a pre-loaded buffer if the model is already in memory.
+ *
+ * The compatibility info can then be passed to GetModelCompatibilityForEpDevices to check if a
+ * precompiled model is compatible with the current system.
+ *
+ * \param[in] model_path Path to the ONNX model file.
+ * \param[in] ep_type The execution provider type string. Must be non-empty.
+ * Use OrtApi::EpDevice_EpName to get this value from an OrtEpDevice.
+ * \param[in] allocator Allocator to use for the output string. Use OrtApi::GetAllocatorWithDefaultOptions.
+ * \param[out] compatibility_info Output pointer to the compatibility info string.
+ * Returns nullptr if no compatibility info exists for the specified EP.
+ * Caller must free with OrtApi::AllocatorFree when non-null.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetCompatibilityInfoFromModel,
+ _In_ const ORTCHAR_T* model_path,
+ _In_ const char* ep_type,
+ _Inout_ OrtAllocator* allocator,
+ _Outptr_result_maybenull_ char** compatibility_info);
+
+ /** \brief Extract EP compatibility info from precompiled model bytes in memory.
+ *
+ * Same as GetCompatibilityInfoFromModel but reads from a memory buffer instead of a file.
+ * Useful when precompiled models are loaded from encrypted storage, network, or other non-file sources.
+ *
+ * \note This API performs standalone model parsing, separate from session creation. This means
+ * the protobuf parsing cost is incurred here and again during session creation. It is intended
+ * for scenarios where applications need to check compatibility before deciding whether to proceed
+ * with session creation, such as providing early user feedback.
+ *
+ * \param[in] model_data Pointer to the model data in memory.
+ * \param[in] model_data_length Size of the model data in bytes.
+ * \param[in] ep_type The execution provider type string. Must be non-empty.
+ * \param[in] allocator Allocator to use for the output string. Use OrtApi::GetAllocatorWithDefaultOptions.
+ * \param[out] compatibility_info Output pointer to the compatibility info string.
+ * Returns nullptr if no compatibility info exists for the specified EP.
+ * Caller must free with OrtApi::AllocatorFree when non-null.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetCompatibilityInfoFromModelBytes,
+ _In_reads_(model_data_length) const void* model_data,
+ _In_ size_t model_data_length,
+ _In_ const char* ep_type,
+ _Inout_ OrtAllocator* allocator,
+ _Outptr_result_maybenull_ char** compatibility_info);
+
+ /// @}
+
+ /** \brief Create an OrtEnv instance with the given options.
+ *
+ * \note Invoking this function will return the same instance of the environment as that returned by a previous call
+ * to another env creation function; all arguments to this function will be ignored.
+ *
+ * \param[in] options The OrtEnvCreationOptions instance that contains creation options.
+ * \param[out] out Output parameter set to the new OrtEnv instance. Must be freed with OrtApi::ReleaseEnv.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(CreateEnvWithOptions, _In_ const OrtEnvCreationOptions* options, _Outptr_ OrtEnv** out);
+
+ /** \brief Get information about the subgraphs assigned to each execution provider (EP) and the nodes within.
+ *
+ * Each returned OrtEpAssignedSubgraph instance contains details of the subgraph/nodes assigned to an execution
+ * provider, including the execution provider's name, and the name, domain, and operator type for every node.
+ *
+ * For compiling execution providers, a single OrtEpAssignedSubgraph instance contains information about the
+ * nodes that are fused and compiled within a single subgraph assigned to the execution provider.
+ *
+ * For execution providers that use kernel registration (e.g., CPU EP), each node with a registered kernel is
+ * contained in its own OrtEpAssignedSubgraph instance.
+ *
+ * \note The caller must enable the collection of this information by enabling the session
+ * configuration entry "session.record_ep_graph_assignment_info" during session creation.
+ * Refer to onnxruntime_session_options_config_keys.h. Otherwise, if not enabled, this function returns a
+ * status with error code ORT_FAIL.
+ *
+ * \note The information reported by this function is obtained immediately after running basic optimizations on the
+ * original graph if the session optimization level is set to ORT_ENABLE_BASIC or higher. If the session
+ * optimization level is set to ORT_DISABLE_ALL, only minimal/required optimizations are run before
+ * the information is collected.
+ *
+ * \param[in] session The OrtSession instance.
+ * \param[out] ep_subgraphs Output parameter set to the array of OrtEpAssignedSubgraph instances.
+ * \param[out] num_ep_subgraphs Output parameter set to the number of elements in the `ep_subgraphs` array.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(Session_GetEpGraphAssignmentInfo, _In_ const OrtSession* session,
+ _Outptr_ const OrtEpAssignedSubgraph* const** ep_subgraphs,
+ _Out_ size_t* num_ep_subgraphs);
+
+ /** \brief Get the name of the execution provider to which the subgraph was assigned.
+ *
+ * \param[in] ep_subgraph The OrtEpAssignedSubgraph instance.
+ * \param[out] out Output parameter set to the execution provider's name as a UTF-8 null-terminated string.
+ * Owned by the OrtEpAssignedSubgraph instance (do not free).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpAssignedSubgraph_GetEpName, _In_ const OrtEpAssignedSubgraph* ep_subgraph,
+ _Outptr_ const char** out);
+
+ /** \brief Get the nodes in a subgraph assigned to a specific execution provider.
+ *
+ * \param[in] ep_subgraph The OrtEpAssignedSubgraph instance.
+ * \param[out] ep_nodes Output parameter set to the array of OrtEpAssignedNode instances.
+ * \param[out] num_ep_nodes Output parameter set to the number of OrtEpAssignedNode instance returned.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpAssignedSubgraph_GetNodes, _In_ const OrtEpAssignedSubgraph* ep_subgraph,
+ _Outptr_ const OrtEpAssignedNode* const** ep_nodes, _Out_ size_t* num_ep_nodes);
+
+ /** \brief Get the name of the node assigned to an execution provider.
+ *
+ * \param[in] ep_node The OrtEpAssignedNode instance.
+ * \param[out] out Output parameter set to the node's name as a UTF-8 null-terminated string.
+ * Owned by the OrtEpAssignedNode instance (do not free).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpAssignedNode_GetName, _In_ const OrtEpAssignedNode* ep_node, _Outptr_ const char** out);
+
+ /** \brief Get the domain of the node assigned to an execution provider.
+ *
+ * \param[in] ep_node The OrtEpAssignedNode instance.
+ * \param[out] out Output parameter set to the node's domain as a UTF-8 null-terminated string.
+ * Owned by the OrtEpAssignedNode instance (do not free).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpAssignedNode_GetDomain, _In_ const OrtEpAssignedNode* ep_node, _Outptr_ const char** out);
+
+ /** \brief Get the operator type of the node assigned to an execution provider.
+ *
+ * \param[in] ep_node The OrtEpAssignedNode instance.
+ * \param[out] out Output parameter set to the node's operator type as a UTF-8 null-terminated string.
+ * Owned by the OrtEpAssignedNode instance (do not free).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpAssignedNode_GetOperatorType, _In_ const OrtEpAssignedNode* ep_node, _Outptr_ const char** out);
+
+ /** \brief Sets OrtSyncStream for the run options
+ *
+ * OrtSyncStream is used to synchronize the execution of the model run for the device
+ * of the stream. It overrides the existing stream for the duration of the Run().
+ * The stream instance must be alive for the duration of the Run() call.
+ *
+ * \param[in] options
+ * \param[in] sync_stream The synchronization stream. Pass nullptr to clear previous setting.
+ *
+ * \since 1.24
+ */
+ ORT_API_T(void, RunOptionsSetSyncStream, _Inout_ OrtRunOptions* options, _In_ OrtSyncStream* sync_stream);
+
+ /** \brief Get the element data type and shape for an OrtValue that represents a Tensor (scalar, dense, or sparse).
+ *
+ * \note This function is an alternative to ::GetTensorTypeAndShape() that does not allocate a new array for
+ * the shape data. The OrtValue instance's internal shape data is returned directly.
+ *
+ * \note Returns an error if the underlying OrtValue is not a Tensor.
+ *
+ * \param[in] value The OrtValue instance.
+ * \param[out] elem_type Output parameter set to the tensor element data type.
+ * \param[out] shape_data Output parameter set to the OrtValue instance's internal shape data array.
+ * For a scalar, `shape_data` is NULL and `shape_data_count` is 0.
+ * Must not be released as it is owned by the OrtValue instance. This pointer becomes invalid
+ * when the OrtValue is released or if the underlying shape data is updated or reallocated.
+ * \param[out] shape_data_count Output parameter set to the number of elements in `shape_data`.
+ * `shape_data_count` is 0 for a scalar.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetTensorElementTypeAndShapeDataReference, _In_ const OrtValue* value,
+ _Out_ ONNXTensorElementDataType* elem_type,
+ _Outptr_result_maybenull_ const int64_t** shape_data,
+ _Out_ size_t* shape_data_count);
+};
+
+/*
+ * Steps to use a custom op:
+ * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops
+ * 2 Create an OrtCustomOp structure for each op and add them to the domain
+ * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options
+ */
+
+// Specifies some characteristics of inputs/outputs of custom ops:
+// Specify if the inputs/outputs are one of:
+// 1) Non-optional (input/output must be present in the node)
+// 2) Optional (input/output may be absent in the node)
+// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands.
+// Only the last input or output of a custom op may be marked as variadic.
+// The homogeneity of the variadic input or output determines whether all operands must be of the same
+// tensor element type.
+typedef enum OrtCustomOpInputOutputCharacteristic {
+ INPUT_OUTPUT_REQUIRED = 0,
+ INPUT_OUTPUT_OPTIONAL,
+ INPUT_OUTPUT_VARIADIC,
+} OrtCustomOpInputOutputCharacteristic;
+
+/*
+ * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by
+ * the implementor of the custom op.
+ */
+struct OrtCustomOp {
+ uint32_t version; // Must be initialized to ORT_API_VERSION
+
+ // This callback creates the kernel, which is a user defined
+ // parameter that is passed to the Kernel* callbacks below. It is
+ // recommended to use CreateKernelV2 which allows for a safe error
+ // propagation by returning an OrtStatusPtr.
+ void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api,
+ _In_ const OrtKernelInfo* info);
+
+ // Returns the name of the op
+ const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op);
+
+ // Returns the type of the execution provider, return nullptr to use CPU execution provider
+ const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op);
+
+ // Returns the count and types of the input & output tensors
+ ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
+ size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op);
+ ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
+ size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op);
+
+ // Perform a computation step. It is recommended to use
+ // KernelComputeV2 which allows for a safe error propagation by
+ // returning an OrtStatusPtr.
+ void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context);
+ void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel);
+
+ // Returns the characteristics of the input & output tensors
+ OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
+ OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
+
+ // Returns the memory type of the input tensors. This API allows the custom op
+ // to place the inputs on specific devices. By default, it returns
+ // OrtMemTypeDefault, which means the input is placed on the default device for
+ // the execution provider. If the inputs need to be with different memory types,
+ // this function can be overridden to return the specific memory types.
+ OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index);
+
+ // Returns the minimum number of input arguments expected for the variadic input.
+ // Applicable only for custom ops that have a variadic input.
+ int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op);
+
+ // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous),
+ // and false (zero) otherwise.
+ // Applicable only for custom ops that have a variadic input.
+ int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op);
+
+ // Returns the minimum number of output values expected for the variadic output.
+ // Applicable only for custom ops that have a variadic output.
+ int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op);
+
+ // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous),
+ // and false (zero) otherwise.
+ // Applicable only for custom ops that have a variadic output.
+ int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op);
+
+ // Create the kernel state which is passed to each compute call.
+ OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api,
+ _In_ const OrtKernelInfo* info,
+ _Out_ void** kernel);
+
+ // Perform the computation step.
+ OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context);
+
+ OrtStatusPtr(ORT_API_CALL* InferOutputShapeFn)(_In_ const struct OrtCustomOp* op, _In_ OrtShapeInferContext*);
+
+ // Get start range
+ int(ORT_API_CALL* GetStartVersion)(_In_ const struct OrtCustomOp* op);
+ int(ORT_API_CALL* GetEndVersion)(_In_ const struct OrtCustomOp* op);
+
+ // Get the inplace_map that defines which output can reuse which input
+ // Callers will provide 2 raw int* and pass in their address, this function will fill these 2 arrays
+ // when return, output (*output_index)[i] may reuse the input (*input_index[i]).
+ // The return value is the size of these 2 arrays.
+ // Callers are responsible to delete these 2 arrays after use by calling OrtCustomOp::ReleaseMayInplace().
+ size_t(ORT_API_CALL* GetMayInplace)(_Out_ int** input_index, _Out_ int** output_index);
+
+ // Release the pointer input_index and output_index allocated from GetMayInplace() function.
+ // If GetMayInplace() is defined, this function MUST be defined as well.
+ void(ORT_API_CALL* ReleaseMayInplace)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index);
+
+ // Same as GetMayInplace() and ReleaseMayInplace()
+ size_t(ORT_API_CALL* GetAliasMap)(_Out_ int** input_index, _Out_ int** output_index);
+ void(ORT_API_CALL* ReleaseAliasMap)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index);
+};
+
+/**
+ * ORT Model Editor API
+ */
+
+/**
+ * \brief The OrtModelEditorApi struct provides functions to create or edit an ONNX model.
+ *
+ * See onnxruntime/test/shared_lib/test_model_editor_api.cc for example usage.
+ *
+ * \since Version 1.22.
+ */
+struct OrtModelEditorApi {
+ // Model building/editing requires a full build. We return nullptr from GetModelEditorApi if this is a minimal
+ // build, so it doesn't matter if there are no function pointers in this struct as a user will never get an
+ // OrtModelEditorApi instance. We do however need a dummy field to avoid empty struct warning.
+#if defined(ORT_MINIMAL_BUILD)
+ const bool not_defined_in_this_build;
+#else
+ /** \brief Create an OrtTypeInfo instance for a Tensor.
+ *
+ * Create an OrtTypeInfo instance for a Tensor to use as graph inputs/outputs with the Model Editor API.
+ *
+ * User can release `tensor_info` after creating the OrtTypeInfo.
+ *
+ * \param[in] tensor_info Tensor type and shape information.
+ * \param[out] type_info TypeInfo instance for the tensor.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Create an OrtTypeInfo instance for a SparseTensor.
+ *
+ * Create an OrtTypeInfo instance for a SparseTensor to use as graph inputs/outputs with the Model Editor API.
+ *
+ * User can release `tensor_info` after creating the OrtTypeInfo.
+ *
+ * \param[in] tensor_info SparseTensor type and shape information.
+ * \param[out] type_info TypeInfo instance for the tensor.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateSparseTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Create an OrtTypeInfo instance for a Map.
+ *
+ * Create an OrtTypeInfo instance for a Map to use as graph inputs/outputs with the Model Editor API.
+ *
+ * User can release `map_value_type` after creating the OrtTypeInfo.
+ *
+ * \param[in] map_key_type Key type for the map.
+ * \param[in] map_value_type Value type for the map.
+ * \param[out] type_info TypeInfo instance for the map.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateMapTypeInfo, ONNXTensorElementDataType map_key_type, _In_ const OrtTypeInfo* map_value_type,
+ _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Create an OrtTypeInfo instance for a Sequence.
+ *
+ * Create an OrtTypeInfo instance for a Sequence to use as graph inputs/outputs with the Model Editor API.
+ *
+ * User can release `sequence_type` after creating the OrtTypeInfo.
+ *
+ * \param[in] sequence_type Sequence type and shape information.
+ * \param[out] type_info TypeInfo instance for the sequence.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateSequenceTypeInfo, _In_ const OrtTypeInfo* sequence_type, _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Create an OrtTypeInfo instance for an Optional.
+ *
+ * Create an OrtTypeInfo instance for an Optional to use as graph inputs/outputs with the Model Editor API.
+ *
+ * User can release `contained_type` after creating the OrtTypeInfo.
+ *
+ * \param[in] contained_type Tensor type and shape information.
+ * \param[out] type_info TypeInfo instance for the tensor.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateOptionalTypeInfo, _In_ const OrtTypeInfo* contained_type, _Outptr_ OrtTypeInfo** type_info);
+
+ /** \brief Create an OrtValueInfo for use as an OrtGraph input or output.
+ *
+ * \param[in] name The name of the input or output.
+ * \param[in] type_info The type information for the input or output. The provided value is copied.
+ * \param[out] value_info The OrtValueInfo instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateValueInfo, _In_ const char* name, _In_ const OrtTypeInfo* type_info,
+ _Outptr_ OrtValueInfo** value_info);
+
+ /** \brief Create an OrtNode to add to an OrtGraph.
+ *
+ * Create an OrtNode.
+ *
+ * Create attributes with CreateOpAttr. OrtOpAttr instances are copied.
+ *
+ * \param[in] operator_name The name of the operator.
+ * \param[in] domain_name The domain of the operator. Use an empty string for ONNX operators.
+ * \param[in] node_name The name of the node.
+ * \param[in] input_names The names of the inputs.
+ * \param[in] input_names_len The number of input names.
+ * \param[in] output_names The names of the outputs.
+ * \param[in] output_names_len The number of output names.
+ * \param[in] attributes The optional attributes of the node.
+ * \param[in] attribs_len The number of attributes. May be zero.
+ * \param[out] node The OrtNode instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateNode, _In_ const char* operator_name, _In_ const char* domain_name, _In_ const char* node_name,
+ _In_reads_(input_names_len) const char* const* input_names, size_t input_names_len,
+ _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len,
+ _In_reads_(attribs_len) _In_opt_ OrtOpAttr** attributes, _In_ size_t attribs_len,
+ _Outptr_ OrtNode** node);
+
+ /** \brief Create an OrtGraph
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateGraph, _Outptr_ OrtGraph** graph);
+
+ /** \brief Set the inputs for the OrtGraph.
+ *
+ * Set the graph inputs. This will replace any existing inputs with the new values.
+ * The OrtGraph takes ownership of the OrtValueInfo instances and you should NOT call ReleaseOrtValueInfo.
+ *
+ * \param[in] graph The OrtGraph instance to update.
+ * \param[in] inputs The input OrtValueInfo instances.
+ * \param[in] inputs_len The number of input OrtValueInfo instances.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(SetGraphInputs, _Inout_ OrtGraph* graph,
+ _In_reads_(inputs_len) _In_ OrtValueInfo** inputs, _In_ size_t inputs_len);
+
+ /** \brief Set the outputs for the OrtGraph.
+ *
+ * Set the graph outputs. This will replace any existing outputs with the new values.
+ * The OrtGraph takes ownership of the OrtValueInfo instances provided and you should NOT call ReleaseOrtValueInfo.
+ *
+ * \param[in] graph The OrtGraph instance to update.
+ * \param[in] outputs The output OrtValueInfo instances.
+ * \param[in] outputs_len The number of output OrtValueInfo instances.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(SetGraphOutputs, _Inout_ OrtGraph* graph,
+ _In_reads_(outputs_len) _In_ OrtValueInfo** outputs, _In_ size_t outputs_len);
+
+ /** \brief Add an initializer to the OrtGraph
+ *
+ * ORT will take ownership of the OrtValue and you should NOT call ReleaseOrtValue.
+ *
+ * Two options:
+ *
+ * Allocated memory:
+ * Use CreateTensorAsOrtValue (allocates memory) and populate the tensor with the data.
+ * Set `data_is_external` to false.
+ *
+ * Pre-existing memory:
+ * Use CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue to create an OrtValue
+ * with a tensor that contains a pointer to the existing data.
+ * Set `data_is_external` to true.
+ *
+ * The pointer must remain valid for the duration of the inference session.
+ * If using CreateTensorWithDataAsOrtValue you are responsible for freeing the memory after the inference session
+ * is released.
+ * If using CreateTensorWithDataAndDeleterAsOrtValue, ORT will free the memory using the provided deleter as
+ * soon as the OrtValue is no longer in use.
+ *
+ * NOTE: A tensor containing pre-existing memory MUST have 128 bytes of data or more.
+ * For smaller tensors use CreateTensorAsOrtValue.
+ *
+ * ONNX shape inferencing does not support external data. An initializer involved in shape inferencing is
+ * typically small (a single value or limited by the rank of a tensor) and uses less than 128 bytes of
+ * memory, so this limit acts as a simple catch-all rule to avoid issues.
+ * e.g. Reshape's `shape`, Clip's `min` and `max`, various ops `axes`.
+ *
+ * \param[in] graph The OrtGraph instance to update.
+ * \param[in] name The value name for the initializer.
+ * \param[in] tensor The OrtValue instance containing the tensor data.
+ * \param[in] data_is_external Set to true if the data is external and should not be copied.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(AddInitializerToGraph, _Inout_ OrtGraph* graph, _In_ const char* name, _In_ OrtValue* tensor,
+ bool data_is_external);
+
+ /** \brief Add an OrtNode to an OrtGraph
+ *
+ * Add the node to the graph. The OrtGraph will take ownership of OrtNode and you should NOT call ReleaseOrtNode.
+ *
+ * \param[in] graph The OrtGraph instance to update.
+ * \param[in] node The OrtNode instance to add to the graph.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(AddNodeToGraph, _Inout_ OrtGraph* graph, _In_ OrtNode* node);
+
+ /** \brief Create an OrtModel.
+ *
+ * Create an OrtModel.
+ *
+ * This can be used to build a new model, or to augment an existing model.
+ *
+ * \param[in] domain_names The domain names for the model.
+ * If augmenting an existing model add additional domains if needed.
+ * \param[in] opset_versions The opset versions for the model.
+ * If augmenting an existing model add additional opset versions if needed.
+ * \param[in] opset_entries_len The number of domain_names and opset_versions entries.
+ * Domain and opset entries should be 1:1
+ * \param[out] model The OrtModel instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateModel,
+ _In_reads_(opset_entries_len) const char* const* domain_names,
+ _In_reads_(opset_entries_len) const int* opset_versions,
+ size_t opset_entries_len,
+ _Outptr_ OrtModel** model);
+
+ /** \brief Add an OrtGraph to an OrtModel.
+ *
+ * Add the graph to a model. This should be called once when creating a new model.
+ *
+ * The OrtModel takes ownership of the OrtGraph and you should NOT call ReleaseOrtGraph.
+ *
+ * \param[in] model The OrtModel instance to update.
+ * \param[in] graph The OrtGraph instance to add to the model.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(AddGraphToModel, _Inout_ OrtModel* model, _In_ OrtGraph* graph);
+
+ /** \brief Create an OrtSession using the OrtModel.
+ *
+ * Create an inference session using the OrtModel instance.
+ * The OrtModel should have been populated with an OrtGraph containing nodes and initializers, and SetGraphInputs
+ * and SetGraphOutputs must have been called.
+ * This will validate the model, run optimizers, and prepare the session for inferencing.
+ *
+ * ReleaseOrtModel must be called to free the OrtModel after session creation.
+ *
+ * \param[in] env The OrtEnv instance.
+ * \param[in] model The OrtModel instance.
+ * \param[in] options The OrtSessionOptions instance.
+ * \param[out] out The OrtSession instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateSessionFromModel, _In_ const OrtEnv* env, _In_ const OrtModel* model,
+ _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out);
+
+ /** \brief Create an OrtSession to augment an existing model.
+ *
+ * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers.
+ * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the
+ * model is finalized.
+ *
+ * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel.
+ * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph.
+ * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made
+ * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes.
+ *
+ * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the
+ * session for inferencing by calling FinalizeModelEditorSession.
+ *
+ * \param{in} env The OrtEnv instance.
+ * \param{in} model_path The path to the existing ONNX model to augment.
+ * \param{in} options The OrtSessionOptions instance.
+ * \param{out} out The created OrtSession instance.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateModelEditorSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path,
+ _In_ const OrtSessionOptions* options,
+ _Outptr_ OrtSession** out);
+
+ /** \brief Create an OrtSession to augment an existing model.
+ *
+ * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers.
+ * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the
+ * model is finalized.
+ *
+ * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel.
+ * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph.
+ * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made
+ * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes.
+ *
+ * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the
+ * session for inferencing by calling FinalizeModelEditorSession.
+ *
+ * \param{in} env The OrtEnv instance.
+ * \param{in} model_data The model data for the existing model to augment.
+ * \param{in} model_data_length The length of the model data.
+ * \param{in} options The OrtSessionOptions instance.
+ * \param{out} out The created OrtSession instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateModelEditorSessionFromArray, _In_ const OrtEnv* env,
+ _In_ const void* model_data, size_t model_data_length,
+ _In_ const OrtSessionOptions* options,
+ _Outptr_ OrtSession** out);
+
+ /** \brief Query the session for the opset version of a domain.
+ *
+ * When using the Model Editor API to augment a model, any new nodes must conform to the opset version of the
+ * original model. To do that the user must be able to discover that opset version.
+ * Returns an error if the domain is not used in the model.
+ *
+ * \param[in] session OrtSession to query
+ * \param[in] domain Domain to query. The ONNX domain is an empty string.
+ * \param[out] opset The opset version of the domain.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(SessionGetOpsetForDomain, _In_ const OrtSession* session, _In_ const char* domain, _Out_ int* opset);
+
+ /** \brief Apply changes to augment the ONNX model in a session created using CreateModelEditorSession[FromArray]
+ *
+ * Adds new nodes and updates graph inputs/outputs using `model` to augment the original ONNX model in the session.
+ * All changes will be validated.
+ * Call FinalizeModelEditorSession to prepare the session for inferencing.
+ *
+ * Existing input/outputs will only be updated if the OrtGraph inputs/outputs are set in the OrtModel.
+ * i.e. you don't need to call SetGraphInputs/SetGraphOutputs if they are unchanged.
+ *
+ * ReleaseOrtModel must be called to free the OrtModel after it is applied to the session.
+ *
+ * \param[in] session OrtSession to update. Session must have been created using CreateModelEditorSession[FromArray].
+ * \param[in] model OrtModel containing new nodes, new initializers, and updated graph input and/or output info.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ApplyModelToModelEditorSession, _Inout_ OrtSession* session, _In_ OrtModel* model);
+
+ /** \brief Finalize the Model Editor session that was created using CreateModelEditorSession[FromArray].
+ *
+ * Finalize the Model Editor session that augmented an ONNX model by adding new nodes.
+ * This will run optimizers and prepare the session for inferencing.
+ *
+ * \param[in] session OrtSession to finalize. Session must have been created using CreateModelEditorSession[FromArray].
+ * \param[in] options OrtSessionOptions to use for the session.
+ * \param[in] prepacked_weights_container Optional OrtPrepackedWeightsContainer to use for the session.
+ Set to nullptr if not used.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(FinalizeModelEditorSession, _Inout_ OrtSession* session, _In_ const OrtSessionOptions* options,
+ _In_opt_ OrtPrepackedWeightsContainer* prepacked_weights_container);
+#endif // !defined(ORT_MINIMAL_BUILD)
+};
+
+/**
+ * ORT Compile API
+ */
+
+/** \brief Flags representing options to enable when compiling a model.
+ */
+typedef enum OrtCompileApiFlags {
+ // Default. Do not enable any additional compilation options.
+ OrtCompileApiFlags_NONE = 0,
+
+ // Force compilation to return an error (ORT_FAIL) if no nodes were compiled.
+ // Otherwise, a model with basic optimizations (ORT_ENABLE_BASIC) is still generated by default.
+ OrtCompileApiFlags_ERROR_IF_NO_NODES_COMPILED = 1 << 0,
+
+ // Force compilation to return an error (ORT_FAIL) if a file with the same filename as the output model exists.
+ // Otherwise, compilation will automatically overwrite the output file if it exists.
+ OrtCompileApiFlags_ERROR_IF_OUTPUT_FILE_EXISTS = 1 << 1,
+} OrtCompileApiFlags;
+
+/**
+ * \brief The OrtCompileApi struct provides functions to compile ONNX models.
+ *
+ * Execution providers that support compilation fuse a subgraph into an EPContext node that wraps a provider-specific
+ * binary representation of the subgraph.
+ * For more details about the EPContext design, refer to:
+ * \htmlonly
+ * <a href="https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html">EPContext design document.</a>
+ * \endhtmlonly
+ *
+ * Example (error handling not shown):
+ * OrtStatus* status = NULL;
+ * OrtCompileApi* compile_api = ort_api->GetCompileApi();
+ * OrtModelCompilationOptions* compile_options = NULL;
+ *
+ * status = compile_api->CreateModelCompilationOptionsFromSessionOptions(env, session_options, &compile_options);
+ * status = compile_api->ModelCompilationOptions_SetInputModelPath(compile_options, ORT_TSTR("model.onnx"));
+ * status = compile_api->ModelCompilationOptions_SetOutputModelPath(compile_options, ORT_TSTR("model.compiled.onnx"));
+ * status = compile_api->CompileModel(env, compile_options);
+ * compile_api->ReleaseModelCompilationOptions(compile_options);
+ *
+ * \since Version 1.22.
+ */
+struct OrtCompileApi {
+ /// \name OrtModelCompilationOptions
+ /// @{
+ ORT_CLASS_RELEASE(ModelCompilationOptions);
+
+ /** \brief Creates an OrtModelCompilationOptions object from an existing OrtSessionOptions object.
+ *
+ * An OrtModelCompilationOptions object contains the settings used to generate a compiled ONNX model.
+ * The OrtSessionOptions object has the execution providers with which the model will be compiled.
+ *
+ * ReleaseOrtModelCompilationsOptions must be called to free the OrtModelCompilationOptions after calling
+ * CompileModel.
+ *
+ * \note By default, the GraphOptimizationLevel is set to ORT_DISABLE_ALL. Use
+ * ModelCompilationOptions_SetGraphOptimizationLevel to enable graph optimizations.
+ *
+ * \param[in] env OrtEnv object.
+ * \param[in] session_options The OrtSessionOptions instance from which to create the OrtModelCompilationOptions.
+ * \param[out] out The created OrtModelCompilationOptions instance.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateModelCompilationOptionsFromSessionOptions, _In_ const OrtEnv* env,
+ _In_ const OrtSessionOptions* session_options, _Outptr_ OrtModelCompilationOptions** out);
+
+ /** \brief Sets the file path to the input ONNX model to compile.
+ *
+ * The input model's location (e.g., file path or memory buffer) must be set with either
+ * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] input_model_path Null terminated string of the path (wchar on Windows, char otherwise).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetInputModelPath, _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ const ORTCHAR_T* input_model_path);
+
+ /** \brief Sets the buffer that stores the bytes of the loaded ONNX model to compile.
+ *
+ * The input model's location (e.g., file path or memory buffer) must be set with either
+ * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] input_model_data Buffer containing the loaded ONNX model bytes.
+ * \param[in] input_model_data_size The number of bytes in the `input_model_data` buffer.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetInputModelFromBuffer,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ const void* input_model_data,
+ size_t input_model_data_size);
+
+ /** \brief Sets the file path for the output ONNX model generated by CompileModel.
+ *
+ * The output model's location (e.g., file path or memory buffer) can be set with either
+ * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer.
+ *
+ * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on
+ * the input model's file path. Examples:
+ * /Path/my_model.onnx -> /Path/my_model_ctx.onnx
+ * /Path/my_model -> /Path/my_model_ctx.onnx
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] output_model_path Null terminated string of the path (wchar on Windows, char otherwise).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelPath, _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ const ORTCHAR_T* output_model_path);
+
+ /** \brief Optionally sets the file that should store external initializers for the compiled ONNX model.
+ * If not set, initializers are stored within the model.
+ *
+ * Only initializers for nodes that were not compiled are stored in the external initializers file.
+ * Compiled nodes contain their initializer data within the `ep_cache_context` attribute of EPContext nodes.
+ * Refer to ModelCompilationOptions_SetEpContextEmbedMode.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] external_initializers_file_path Null terminated string of the path to the file.
+ * \param[in] external_initializers_size_threshold Initializers larger than this threshold are stored in the file.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelExternalInitializersFile,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ const ORTCHAR_T* external_initializers_file_path,
+ size_t external_initializers_size_threshold);
+
+ /** \brief Configures model compilation to store the output compiled ONNX model in a buffer.
+ *
+ * The caller passes an OrtAllocator that ONNX Runtime uses to allocate memory for the buffer.
+ *
+ * The output model's location (e.g., file path or memory buffer) can be set with either
+ * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer.
+ *
+ * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on
+ * the input model's file path. Examples:
+ * /Path/my_model.onnx -> /Path/my_model_ctx.onnx
+ * /Path/my_model -> /Path/my_model_ctx.onnx
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] allocator The allocator used to allocate the buffer for the compiled model.
+ * \param[out] output_model_buffer_ptr Pointer to the buffer that stores the compiled model.
+ * \param[out] output_model_buffer_size_ptr Pointer set to the size of output model in bytes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelBuffer,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _Inout_ OrtAllocator* allocator,
+ _Outptr_ void** output_model_buffer_ptr,
+ _Out_ size_t* output_model_buffer_size_ptr);
+
+ /** \brief Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute
+ * of EPContext nodes. Defaults to false.
+ *
+ * If enabled, the `ep_cache_context` attribute of EPContext nodes will store the context binary data, which may
+ * include weights for compiled subgraphs.
+ *
+ * If disabled, the `ep_cache_context` attribute of EPContext nodes will contain the path to the file containing the
+ * context binary data. The path is set by the execution provider creating the EPContext node.
+ *
+ * More details relate to EPContext design refers to:
+ * \htmlonly
+ * <a href="https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html">EPContext design document.</a>
+ * \endhtmlonly
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] embed_ep_context_in_model True to embed EPContext binary data into the EPContext node
+ * `ep_cache_context` attributes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetEpContextEmbedMode, _In_ OrtModelCompilationOptions* model_compile_options,
+ bool embed_ep_context_in_model);
+
+ /** \brief Compiles an input ONNX model with the given compilation options.
+ *
+ * \param[in] env OrtEnv object.
+ * \param[in] model_options The compilation options that defines compilation options for a model.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CompileModel, _In_ const OrtEnv* env, _In_ const OrtModelCompilationOptions* model_options);
+
+ /** \brief Sets flags from OrtCompileApiFlags that represent one or more boolean options to enable.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] flags bitwise OR of flags in OrtCompileApiFlags to enable.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetFlags, _In_ OrtModelCompilationOptions* model_compile_options,
+ uint32_t flags);
+
+ /** Sets information related to EP context binary file.
+ *
+ * EP uses this information to decide the location and context binary file name.
+ * Used while compiling model with input and output in memory buffer
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] output_directory Null terminated string of the path (wchar on Windows, char otherwise).
+ * \param[in] model_name Null terminated string of the model name (wchar on Windows, char otherwise).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetEpContextBinaryInformation,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ const ORTCHAR_T* output_directory,
+ _In_ const ORTCHAR_T* model_name);
+
+ /** Set the graph optimization level.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] graph_optimization_level The graph optimization level.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetGraphOptimizationLevel,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ GraphOptimizationLevel graph_optimization_level);
+
+ /** \brief Sets a OrtWriteBufferFunc function that is called by ORT to write out the output model's serialized
+ * ONNX bytes.
+ *
+ * The provided write function may be called repeatedly until then entire output model has been written out. Each call
+ * to the write function is expected to consume the entire input buffer.
+ *
+ * The output model's destination (e.g., file path, memory buffer, or stream) can be set with any of the functions
+ * that begin with ModelCompilationOptions_SetOutputModel____.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] write_func The OrtWriteBufferFunc function called by ORT when writing out the model.
+ * \param[in] state Opaque state passed as the first argument to OrtWriteBufferFunc. Can be NULL.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelWriteFunc,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ OrtWriteBufferFunc write_func, _In_ void* state);
+
+ /** \brief Sets a OrtGetInitializerLocationFunc function that is called by ORT for every initializer in the generated
+ * model. Allows implementer to specify whether initializers should be stored within the model or externally.
+ *
+ * \param[in] model_compile_options The OrtModelCompilationOptions instance.
+ * \param[in] get_initializer_location_func The OrtGetInitializerLocationFunc function called by ORT when
+ * to determine the location of the initializer.
+ * \param[in] state Opaque state passed as the first argument to OrtGetInitializerLocationFunc. Can be NULL.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelGetInitializerLocationFunc,
+ _In_ OrtModelCompilationOptions* model_compile_options,
+ _In_ OrtGetInitializerLocationFunc get_initializer_location_func, _In_ void* state);
+};
+
+/**
+ * \brief The OrtInteropApi struct provides functions for external resource interop with execution providers.
+ *
+ * This API enables importing external GPU resources (memory and semaphores) for zero-copy sharing
+ * between ORT inference and other GPU workloads (e.g., D3D12 applications, media pipelines).
+ *
+ * The API is designed to be EP-agnostic and can be extended to support various GPU interop mechanisms
+ * (D3D12 shared handles, CUDA external memory, Vulkan, etc.).
+ *
+ * Example usage (error handling not shown):
+ * const OrtInteropApi* interop_api = ort_api->GetInteropApi();
+ * OrtExternalResourceImporter* importer = NULL;
+ *
+ * status = interop_api->CreateExternalResourceImporterForDevice(ep_device, &importer);
+ * if (importer == nullptr) {
+ * // External resource import is optional for EPs to implement
+ * return;
+ * }
+ * bool can_import = false;
+ * status = interop_api->CanImportMemory(importer, ORT_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE, &can_import);
+ * if (can_import) {
+ * OrtExternalMemoryHandle* mem_handle = NULL;
+ * status = interop_api->ImportMemory(importer, &mem_desc, &mem_handle);
+ * // ... use mem_handle to create tensors ...
+ * interop_api->ReleaseExternalMemoryHandle(mem_handle);
+ * }
+ * interop_api->ReleaseExternalResourceImporter(importer);
+ *
+ * \since Version 1.24.
+ */
+struct OrtInteropApi {
+ /// \name OrtExternalResourceImporter
+ /// @{
+
+ /** \brief Create an external resource importer for a specific EP device.
+ *
+ * The external resource importer is a capability object that provides methods for importing
+ * external GPU memory and semaphores for zero-copy import with an execution provider.
+ *
+ * This is an optional EP capability. If the EP does not support external resource import,
+ * out_importer is set to nullptr and the function returns success (nullptr status).
+ * This allows callers to use the simple "if (status != nullptr) handle_error()" pattern
+ * and check out_importer separately for capability detection.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to create the importer for.
+ * \param[out] out_importer Output parameter set to the created OrtExternalResourceImporter instance,
+ * or nullptr if the EP does not support external resource import.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateExternalResourceImporterForDevice,
+ _In_ const OrtEpDevice* ep_device,
+ _Outptr_result_maybenull_ OrtExternalResourceImporter** out_importer);
+
+ /** \brief Release an OrtExternalResourceImporter instance.
+ *
+ * \param[in] input The OrtExternalResourceImporter instance to release. May be nullptr.
+ *
+ * \since Version 1.24.
+ */
+ ORT_CLASS_RELEASE(ExternalResourceImporter);
+
+ /// @}
+ /// \name Memory Import
+ /// @{
+
+ /** \brief Check if the external resource importer can import a specific memory handle type.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] handle_type The type of external memory handle to check.
+ * \param[out] out_supported Set to true if the handle type is supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CanImportMemory,
+ _In_ const OrtExternalResourceImporter* importer,
+ _In_ OrtExternalMemoryHandleType handle_type,
+ _Out_ bool* out_supported);
+
+ /** \brief Import external memory into the execution provider.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] desc Descriptor containing the external memory handle and properties.
+ * \param[out] out_handle Output parameter set to the created OrtExternalMemoryHandle.
+ * The caller owns the returned handle and must call ReleaseExternalMemoryHandle to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(ImportMemory,
+ _In_ OrtExternalResourceImporter* importer,
+ _In_ const OrtExternalMemoryDescriptor* desc,
+ _Outptr_ OrtExternalMemoryHandle** out_handle);
+
+ /** \brief Release an OrtExternalMemoryHandle instance.
+ *
+ * \param[in] input The OrtExternalMemoryHandle instance to release. May be nullptr.
+ *
+ * \since Version 1.24.
+ */
+ ORT_CLASS_RELEASE(ExternalMemoryHandle);
+
+ /** \brief Create a tensor backed by imported external memory.
+ *
+ * The created tensor is a view over the imported memory and does not copy data.
+ * The OrtExternalMemoryHandle must remain valid for the lifetime of the tensor.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] mem_handle The imported external memory handle.
+ * \param[in] tensor_desc Descriptor specifying tensor element type, shape, and optional offset.
+ * \param[out] out_tensor Output parameter set to the created OrtValue containing the tensor.
+ * The caller owns the returned tensor and must call ReleaseValue to free it.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateTensorFromMemory,
+ _In_ OrtExternalResourceImporter* importer,
+ _In_ const OrtExternalMemoryHandle* mem_handle,
+ _In_ const OrtExternalTensorDescriptor* tensor_desc,
+ _Outptr_ OrtValue** out_tensor);
+
+ /// @}
+ /// \name Semaphore Import
+ /// @{
+
+ /** \brief Check if the external resource importer can import a specific semaphore type.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] type The type of external semaphore to check.
+ * \param[out] out_supported Set to true if the semaphore type is supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CanImportSemaphore,
+ _In_ const OrtExternalResourceImporter* importer,
+ _In_ OrtExternalSemaphoreType type,
+ _Out_ bool* out_supported);
+
+ /** \brief Import an external semaphore into the execution provider.
+ *
+ * The returned OrtExternalSemaphoreHandle can be used with WaitSemaphore and an OrtSyncStream
+ * to synchronize execution with external operations.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] desc Descriptor containing the external semaphore handle and type.
+ * \param[out] out_handle Output parameter set to the created OrtExternalSemaphoreHandle.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(ImportSemaphore,
+ _In_ OrtExternalResourceImporter* importer,
+ _In_ const OrtExternalSemaphoreDescriptor* desc,
+ _Outptr_ OrtExternalSemaphoreHandle** out_handle);
+
+ /** \brief Release an OrtExternalSemaphoreHandle instance.
+ *
+ * \param[in] input The OrtExternalSemaphoreHandle instance to release. May be nullptr.
+ *
+ * \since Version 1.24.
+ */
+ ORT_CLASS_RELEASE(ExternalSemaphoreHandle);
+
+ /** \brief Wait on an external semaphore on the EP's stream.
+ *
+ * Inserts a wait operation into the EP's stream that blocks until the semaphore
+ * reaches the specified value. This is used to synchronize with external GPU work
+ * (e.g., D3D12 timeline fence).
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] semaphore_handle The imported external semaphore.
+ * \param[in] stream The OrtSyncStream to wait on.
+ * \param[in] value The fence/semaphore value to wait for.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(WaitSemaphore,
+ _In_ OrtExternalResourceImporter* importer,
+ _In_ OrtExternalSemaphoreHandle* semaphore_handle,
+ _In_ OrtSyncStream* stream,
+ _In_ uint64_t value);
+
+ /** \brief Signal an external semaphore from the EP's stream.
+ *
+ * Inserts a signal operation into the EP's stream that sets the semaphore
+ * to the specified value when reached. This is used to notify external GPU work
+ * (e.g., D3D12 timeline fence) that ORT inference is complete.
+ *
+ * \param[in] importer The OrtExternalResourceImporter instance.
+ * \param[in] semaphore_handle The imported external semaphore.
+ * \param[in] stream The OrtSyncStream to signal from.
+ * \param[in] value The fence/semaphore value to signal.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(SignalSemaphore,
+ _In_ OrtExternalResourceImporter* importer,
+ _In_ OrtExternalSemaphoreHandle* semaphore_handle,
+ _In_ OrtSyncStream* stream,
+ _In_ uint64_t value);
+
+ /// @}
+};
+
+/*
+ * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality
+ * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists
+ *
+ * \param device_id CUDA device id, starts from zero.
+ */
+ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id);
+
+/*
+ * This is the old way to add the ROCm provider to the session, please use
+ * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality
+ * This function always exists, but will only succeed if Onnxruntime was built with
+ * HIP support and the ROCm provider shared library exists
+ *
+ * \param device_id HIP device id, starts from zero.
+ */
+ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id);
+
+/*
+ * This is the old way to add the MIGraphX provider to the session, please use
+ * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality
+ * This function always exists, but will only succeed if Onnxruntime was built with
+ * HIP support and the MIGraphX provider shared library exists
+ *
+ * \param device_id HIP device id, starts from zero.
+ */
+ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id);
+
+/*
+ * This is the old way to add the oneDNN provider to the session, please use
+ * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality
+ * This function always exists, but will only succeed if Onnxruntime was built with
+ * oneDNN support and the oneDNN provider shared library exists
+ *
+ * \param use_arena zero: false. non-zero: true.
+ */
+ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena);
+
+/*
+ * This is the old way to add the TensorRT provider to the session, please use SessionOptionsAppendExecutionProvider_TensorRT_V2 above to access the latest functionality
+ * This function always exists, but will only succeed if Onnxruntime was built with TensorRT support and the TensorRT provider shared library exists
+ *
+ * \param device_id CUDA device id, starts from zero.
+ */
+ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id);
+
+#ifdef __cplusplus
+}
+#endif
+/// @}
+
+#include "onnxruntime_ep_c_api.h"
diff --git a/kernel/ocr/onnxruntime_ep_c_api.h b/kernel/ocr/onnxruntime_ep_c_api.h
new file mode 100644
index 0000000000..b888d0d609
--- /dev/null
+++ b/kernel/ocr/onnxruntime_ep_c_api.h
@@ -0,0 +1,2112 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// Licensed under the MIT License.
+
+// Do not include this file directly. Please include "onnxruntime_c_api.h" instead.
+
+#if defined(__DOXYGEN__)
+// When running a Doxygen build, include onnxruntime_c_api.h. Doxygen expects header files to be self-contained.
+#include "onnxruntime_c_api.h"
+#else
+// In normal usage, do not include onnxruntime_c_api.h. This file is explicitly included in onnxruntime_c_api.h.
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ORT_RUNTIME_CLASS(Ep);
+ORT_RUNTIME_CLASS(EpFactory);
+ORT_RUNTIME_CLASS(EpGraphSupportInfo);
+ORT_RUNTIME_CLASS(MemoryDevice); // opaque class to wrap onnxruntime::OrtDevice
+ORT_RUNTIME_CLASS(NodeComputeContext);
+
+ORT_RUNTIME_CLASS(DataTransferImpl);
+ORT_RUNTIME_CLASS(SyncNotificationImpl);
+ORT_RUNTIME_CLASS(SyncStreamImpl);
+
+ORT_RUNTIME_CLASS(ExternalResourceImporterImpl);
+
+/** \brief Base struct for imported external memory handles.
+ *
+ * EPs derive from this struct to add EP-specific fields (e.g., CUdeviceptr for CUDA).
+ * EP is responsible for creating and releasing instances of the derived type.
+ *
+ * Example derived type for CUDA EP:
+ * \code
+ * struct MyCudaExternalMemoryHandle : OrtExternalMemoryHandle {
+ * CUexternalMemory ext_memory;
+ * CUdeviceptr mapped_ptr;
+ * bool is_dedicated;
+ * };
+ * \endcode
+ *
+ * \since Version 1.24.
+ */
+struct OrtExternalMemoryHandle {
+ uint32_t version; ///< Must be ORT_API_VERSION
+ const OrtEpDevice* ep_device; ///< EP device that created this handle
+ OrtExternalMemoryDescriptor descriptor; ///< External memory descriptor
+
+ /** \brief Release callback for this handle. EP sets this to its release function.
+ *
+ * ORT calls this when ReleaseExternalMemoryHandle is invoked. The EP's callback
+ * should cast the handle to its derived type and delete it.
+ */
+ void(ORT_API_CALL* Release)(_In_ OrtExternalMemoryHandle* handle);
+};
+
+/** \brief Base struct for imported external semaphore handles.
+ *
+ * EPs derive from this struct to add EP-specific fields (e.g., CUexternalSemaphore for CUDA).
+ * EP is responsible for creating and releasing instances of the derived type.
+ *
+ * Example derived type for CUDA EP:
+ * \code
+ * struct MyCudaExternalSemaphoreHandle : OrtExternalSemaphoreHandle {
+ * CUexternalSemaphore ext_semaphore;
+ * };
+ * \endcode
+ *
+ * \since Version 1.24.
+ */
+struct OrtExternalSemaphoreHandle {
+ uint32_t version; ///< Must be ORT_API_VERSION
+ const OrtEpDevice* ep_device; ///< EP device that created this handle
+ OrtExternalSemaphoreDescriptor descriptor; ///< External semaphore descriptor
+
+ /** \brief Release callback for this handle. EP sets this to its release function.
+ *
+ * ORT calls this when ReleaseExternalSemaphoreHandle is invoked. The EP's callback
+ * should cast the handle to its derived type and delete it.
+ */
+ void(ORT_API_CALL* Release)(_In_ OrtExternalSemaphoreHandle* handle);
+};
+
+// Opaque types for kernel-based EPs
+ORT_RUNTIME_CLASS(KernelRegistry);
+ORT_RUNTIME_CLASS(KernelDefBuilder);
+ORT_RUNTIME_CLASS(KernelDef);
+ORT_RUNTIME_CLASS(DataType); // combination of ONNXType (e.g., Tensor, Map, Sequence) and ONNXTensorElementDataType
+ORT_RUNTIME_CLASS(SharedPrePackedWeightCache);
+
+/** \brief Struct that an EP implements for IDataTransfer to copy between devices it uses and CPU.
+ *
+ * \since Version 1.23.
+ */
+struct OrtDataTransferImpl {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ /** \brief Release the OrtDataTransferImpl instance.
+ *
+ * This is called by ORT when the OrtDataTransferImpl instance is no longer needed.
+ * The implementation should release any resources held by the instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtDataTransferImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void, Release, _In_ OrtDataTransferImpl* this_ptr);
+
+ /** \brief Check if the implementation can copy between the source and destination memory devices.
+ *
+ * \param[in] this_ptr Pointer to the OrtDataTransferImpl instance.
+ * \param[in] src_memory_device Source OrtMemoryDevice to copy from.
+ * \param[in] dst_memory_device Destination OrtMemoryDevice to copy to.
+ * \return True if the implementation can copy between the devices.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(bool, CanCopy, _In_ const OrtDataTransferImpl* this_ptr,
+ _In_ const OrtMemoryDevice* src_memory_device, _In_ const OrtMemoryDevice* dst_memory_device);
+
+ /** \brief Copy tensors from src_tensors to dst_tensors using the provided streams.
+ *
+ * The implementation can use the provided streams to perform asynchronous copies if supported.
+ * If a stream is not available, the copy is performed synchronously.
+ *
+ * \param[in] this_ptr Pointer to the OrtDataTransferImpl instance.
+ * \param[in] src_tensors Array of source OrtValue pointers to copy from.
+ * \param[in] dst_tensors Array of destination OrtValue pointers to copy to.
+ * \param[in] streams Array of OrtSyncStream pointers for the copy operations, if the execution provider is stream
+ * aware. nullptr if it is not.
+ * \param[in] num_tensors Number of tensors to copy.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CopyTensors, _In_ OrtDataTransferImpl* this_ptr,
+ _In_reads_(num_tensors) const OrtValue** src_tensors,
+ _In_reads_(num_tensors) OrtValue** dst_tensors,
+ _In_reads_(num_tensors) OrtSyncStream** streams,
+ _In_ size_t num_tensors);
+};
+
+/** \brief Struct that an EP implements for Stream Notifications.
+ *
+ * \since Version 1.23.
+ */
+struct OrtSyncNotificationImpl {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ /** \brief Release the OrtSyncNotificationImpl instance.
+ *
+ * This is called by ORT when the OrtSyncNotificationImpl instance is no longer needed.
+ * The implementation should release any resources held by the instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncNotificationImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void, Release, _In_ OrtSyncNotificationImpl* this_ptr);
+
+ /** \brief Called by ORT to activate the notification.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncNotificationImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Activate, _In_ OrtSyncNotificationImpl* this_ptr);
+
+ /** \brief Wait for a device to device operation to complete.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncNotificationImpl instance.
+ * \param[in] consumer_stream The OrtSyncStream instance that will wait on this notification to be activated.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(WaitOnDevice, _In_ OrtSyncNotificationImpl* this_ptr, _In_ OrtSyncStream* consumer_stream);
+
+ /** \brief Wait for a device to host operation to complete.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncNotificationImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(WaitOnHost, _In_ OrtSyncNotificationImpl* this_ptr);
+};
+
+/** \brief Struct that an EP implements if it wishes to implement Stream support.
+ *
+ * This struct provides the overrides for onnxruntime::Stream's virtual methods.
+ *
+ * \since Version 1.23.
+ */
+struct OrtSyncStreamImpl {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ /** \brief Release the OrtSyncStreamImpl instance.
+ *
+ * This is called by ORT when the OrtSyncStreamImpl instance is no longer needed.
+ * The implementation should release any resources held by the instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncStreamImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void, Release, _In_ OrtSyncStreamImpl* this_ptr);
+
+ /** \brief Get the handle of the stream.
+ *
+ * This returns the native handle for the stream. e.g. cudaStream_t for CUDA streams.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncStreamImpl instance.
+ * \return The handle of the stream.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void*, GetHandle, _In_ OrtSyncStreamImpl* this_ptr);
+
+ /** \brief Create an OrtSyncNotificationImpl for the OrtSyncStreamImpl instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncStreamImpl instance
+ * \param[out] notification The new OrtSyncNotificationImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateNotification, _In_ OrtSyncStreamImpl* this_ptr,
+ _Outptr_ OrtSyncNotificationImpl** notification);
+
+ /** \brief Flush the stream.
+ *
+ * This is called by ORT to flush the stream, ensuring that all operations submitted to the stream are completed.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncStreamImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Flush, _In_ OrtSyncStreamImpl* this_ptr);
+
+ /** \brief Notify the stream that a session run has ended.
+ *
+ * This is called by ORT to notify the stream that a session run has ended, allowing the stream to perform any
+ * necessary cleanup or finalization.
+ *
+ * \param[in] this_ptr Pointer to the OrtSyncStreamImpl instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OnSessionRunEnd, _In_ OrtSyncStreamImpl* this_ptr);
+};
+
+/** \brief Struct that an EP implements for external resource import (memory + semaphore import).
+ *
+ * This capability object provides methods for importing external GPU memory and semaphores
+ * for zero-copy import. EPs that support D3D12, CUDA, HIP, or Vulkan external resource APIs
+ * can implement this interface.
+ *
+ * \since Version 1.24.
+ */
+struct OrtExternalResourceImporterImpl {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ // Memory operations (stream-independent)
+
+ /** \brief Check if the implementation can import external memory of the given handle type.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] handle_type The type of external memory handle to check.
+ * \return True if the handle type is supported.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(bool, CanImportMemory,
+ _In_ const OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalMemoryHandleType handle_type);
+
+ /** \brief Import external memory.
+ *
+ * The EP creates a derived type of OrtExternalMemoryHandle and returns a pointer to the base.
+ * EP is responsible for the lifetime of the handle (release via ReleaseMemory).
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] desc Descriptor containing the external memory handle and properties.
+ * \param[out] out_handle Output parameter set to the created OrtExternalMemoryHandle (EP's derived type).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(ImportMemory,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ const OrtExternalMemoryDescriptor* desc,
+ _Outptr_ OrtExternalMemoryHandle** out_handle);
+
+ /** \brief Release an imported external memory handle.
+ *
+ * The EP deletes its derived type instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] handle The OrtExternalMemoryHandle to release (EP casts to its derived type).
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, ReleaseMemory,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalMemoryHandle* handle);
+
+ /** \brief Create a tensor backed by imported external memory.
+ *
+ * The created tensor is a view over the imported memory and does not copy data.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] mem_handle The imported external memory handle (EP casts to its derived type).
+ * \param[in] tensor_desc Descriptor specifying tensor element type, shape, and optional offset.
+ * \param[out] out_tensor Output parameter set to the created OrtValue containing the tensor.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateTensorFromMemory,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ const OrtExternalMemoryHandle* mem_handle,
+ _In_ const OrtExternalTensorDescriptor* tensor_desc,
+ _Outptr_ OrtValue** out_tensor);
+
+ // Semaphore operations (require stream)
+
+ /** \brief Check if the implementation can import external semaphores of the given type.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] type The type of external semaphore to check.
+ * \return True if the semaphore type is supported.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(bool, CanImportSemaphore,
+ _In_ const OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalSemaphoreType type);
+
+ /** \brief Import an external semaphore.
+ *
+ * The EP creates a derived type of OrtExternalSemaphoreHandle and returns a pointer to the base.
+ * EP is responsible for the lifetime of the handle (release via ReleaseSemaphore).
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] desc Descriptor containing the external semaphore handle and type.
+ * \param[out] out_handle Output parameter set to the created OrtExternalSemaphoreHandle (EP's derived type).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(ImportSemaphore,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ const OrtExternalSemaphoreDescriptor* desc,
+ _Outptr_ OrtExternalSemaphoreHandle** out_handle);
+
+ /** \brief Release an imported external semaphore handle.
+ *
+ * The EP deletes its derived type instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] handle The OrtExternalSemaphoreHandle to release (EP casts to its derived type).
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, ReleaseSemaphore,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalSemaphoreHandle* handle);
+
+ /** \brief Wait on an external semaphore on the EP's stream.
+ *
+ * Inserts a wait operation into the EP's stream that blocks until the semaphore
+ * reaches the specified value.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] handle The imported external semaphore (EP casts to its derived type).
+ * \param[in] stream The OrtSyncStream to wait on.
+ * \param[in] value The fence/semaphore value to wait for.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(WaitSemaphore,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalSemaphoreHandle* handle,
+ _In_ OrtSyncStream* stream,
+ _In_ uint64_t value);
+
+ /** \brief Signal an external semaphore from the EP's stream.
+ *
+ * Inserts a signal operation into the EP's stream that sets the semaphore
+ * to the specified value when reached.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ * \param[in] handle The imported external semaphore (EP casts to its derived type).
+ * \param[in] stream The OrtSyncStream to signal from.
+ * \param[in] value The fence/semaphore value to signal.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(SignalSemaphore,
+ _In_ OrtExternalResourceImporterImpl* this_ptr,
+ _In_ OrtExternalSemaphoreHandle* handle,
+ _In_ OrtSyncStream* stream,
+ _In_ uint64_t value);
+
+ // Release the capability object itself
+
+ /** \brief Release the OrtExternalResourceImporterImpl instance.
+ *
+ * This is called by ORT when the OrtExternalResourceImporterImpl instance is no longer needed.
+ * The implementation should release any resources held by the instance.
+ *
+ * \param[in] this_ptr Pointer to the OrtExternalResourceImporterImpl instance.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, Release, _In_ OrtExternalResourceImporterImpl* this_ptr);
+};
+
+struct OrtNodeFusionOptions;
+typedef struct OrtNodeFusionOptions OrtNodeFusionOptions;
+
+struct OrtNodeComputeInfo;
+typedef struct OrtNodeComputeInfo OrtNodeComputeInfo;
+
+/**
+ * \brief The OrtNodeFusionOptions struct specifies options for fusing nodes supported by an execution provider.
+ *
+ * Refer to OrtEpApi::EpGraphSupportInfo_AddNodesToFuse.
+ *
+ * \since Version 1.23.
+ */
+struct OrtNodeFusionOptions {
+ /** \brief The ONNX Runtime version the OrtNodeFusionOptions was compiled with.
+ *
+ * Implementation should set to ORT_API_VERSION.
+ * ORT will use this to ensure it does not use members that were not available when the EP library was compiled.
+ *
+ * \since Version 1.23.
+ */
+ uint32_t ort_version_supported;
+
+ /** \brief If set to true, specify that the execution provider does not require ONNX Runtime to provide constant
+ * initializers as inputs to the fused node during model inference. This is used when the execution
+ * provider saves a copy of constant initializers, and allows ONNX Runtime to release constant initializers that
+ * are not used by any execution provider.
+ *
+ * If not specified, defaults to false. That is, ONNX Runtime provides constant initializers as inputs to
+ * the fused node by default.
+ *
+ * \since Version 1.23.
+ */
+ bool drop_constant_initializers;
+
+ // const OrtNode* fused_node_schema;
+};
+
+/**
+ * \brief The OrtNodeComputeInfo struct provides functions that an OrtEp implements to specify the compute
+ * function for a compiled OrtGraph instance.
+ * \since Version 1.23.
+ */
+struct OrtNodeComputeInfo {
+ /** \brief The ONNX Runtime version the OrtNodeComputeInfo was compiled with.
+ *
+ * Implementation should set to ORT_API_VERSION.
+ * ORT will use this to ensure it does not call functions that were not available when the EP library was compiled.
+ *
+ * \since Version 1.23.
+ */
+ uint32_t ort_version_supported;
+
+ /** \brief Creates an opaque compute state object that is then passed to the Compute() function during inference.
+ * \param[in] this_ptr The OrtNodeComputeInfo instance.
+ * \param[in] compute_context OrtNodeComputeContext instance that contains compiled/fused node's name and host
+ * memory allocation functions. Can optionally be used to build the compute state.
+ * \param[out] compute_state Output parameter that is assigned the opaque computation state. ONNX Runtime calls
+ * ReleaseState() (after calling Compute()) to allow the implementer to release the
+ * compute state.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ OrtStatus*(ORT_API_CALL* CreateState)(_In_ OrtNodeComputeInfo* this_ptr,
+ _In_ OrtNodeComputeContext* compute_context,
+ _Outptr_ void** compute_state);
+
+ /** \brief Computation function called to execute the fused node compiled by an OrtEp instance.
+ * \param[in] this_ptr The OrtNodeComputeInfo instance.
+ * \param[in] compute_state The opaque computation state returned by CreateState().
+ * \param[in] kernel_context The OrtKernelContext instance used to access inputs/outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ OrtStatus*(ORT_API_CALL* Compute)(_In_ OrtNodeComputeInfo* this_ptr, _In_ void* compute_state,
+ _In_ OrtKernelContext* kernel_context);
+
+ /** \brief Releases the compute state returned by CreateState().
+ * \param[in] this_ptr The OrtNodeComputeInfo instance.
+ * \param[inout] compute_state The opaque compute state returned by CreateState().
+ *
+ * \since Version 1.23.
+ */
+ void(ORT_API_CALL* ReleaseState)(_In_ OrtNodeComputeInfo* this_ptr, _Frees_ptr_opt_ void* compute_state);
+};
+
+struct OrtKernelImpl;
+typedef struct OrtKernelImpl OrtKernelImpl;
+
+/**
+ * \brief Contains functions that an OrtEp implements to specify the computation for an operator kernel.
+ * \since Version 1.24.
+ */
+struct OrtKernelImpl {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+ uint32_t flags; ///< EP must initialize to 0. Used internally by ORT.
+
+ /** \brief Computation function called to execute the kernel on an EP.
+ *
+ * \note Implementation of this function is required.
+ *
+ * \param[in] this_ptr The OrtKernelImpl instance.
+ * \param[in] context The OrtKernelContext instance that provides access to the inputs and outputs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(Compute, _In_ OrtKernelImpl* this_ptr, _In_ OrtKernelContext* context);
+
+ /** \brief Called by ORT to release the OrtKernelImpl instance and its resources.
+ *
+ * \note Implementation of this function is required.
+ *
+ * \param[in] this_ptr The OrtKernelImpl instance.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, Release, _In_ OrtKernelImpl* this_ptr);
+
+ /** \brief Optional function to pre-pack a constant tensor (i.e., a weight) to the kernel's preferred data layout.
+ *
+ * For example, a Conv kernel can define this function to pack input W to the channel-last data layout
+ * before inference.
+ *
+ * Pre-packing can operate in three different modes: no pre-packing mode, sharing mode, and non-sharing mode.
+ * 1) No pre-packing mode: The kernel can forgo any weight pre-packing for the given `input_index` by setting
+ * `is_packed` to false and returning a successful OrtStatus. In this mode, the kernel's
+ * OrtKernelImpl::SetSharedPrePackedWeight() function is not called for that specific
+ * `input_index`.
+ * 2) Sharing mode: Sharing is allowed if the `prepacked_weight_cache` argument is not NULL and the EP stores
+ * weight data in CPU-accessible memory. In this case, the kernel can optionally choose
+ * to share the packed weight with other kernels that use the same weight
+ * (compared by content hash). To do so, the kernel must allocate the packed weight with the
+ * provided `allocator`, then it stores the packed weight data into `prepacked_weight_cache`
+ * via SharedPrePackedWeightCache_StoreWeightData(), sets `is_packed` to true, and returns a
+ * successful OrtStatus. ORT will subsequently call OrtKernelImpl::SetSharedPrePackedWeight()
+ * to provide this kernel with the actual shared weight data, whose memory location could
+ * differ (i.e., if shared data was allocated by a previously processed kernel).
+ * 3) Non-sharing mode: In non-sharing mode, the `prepacked_weight_cache` argument is ignored. In this mode,
+ * the implementation allocates the packed data with the provided `allocator`, sets
+ * `is_packed` to true, and returns a successful OrtStatus. The kernel is ultimately
+ * responsible for releasing the packed data for the weight with `allocator`.
+ * ORT may release the original (unpacked) weight, which must not be accessed in
+ * OrtKernelImpl::Compute(). Note that in this mode, the kernel's
+ * OrtKernelImpl::SetSharedPrePackedWeight() function is not called by ORT for that specific
+ * `input_index`.
+ *
+ * \note This function is based on the internal OpKernel::PrePack() virtual function used within ORT.
+ *
+ * \param[in] this_ptr The OrtKernelImpl instance.
+ * \param[in] tensor The OrtValue instance representing the constant tensor (weight). Do not cache in the kernel.
+ * \param[in] input_index The input index of the tensor in this kernel.
+ * \param[in] allocator Allocator for allocating the pre-packed data. Its use is required in sharing mode and
+ * recommended, but not required, in the non-sharing mode. This will be an allocator set by
+ * the application for the session/environment (e.g., via CreateAndRegisterAllocator[V2]
+ * or RegisterAllocator), or an allocator on the OrtEpDevice (read-only or default) otherwise.
+ * The allocator remains valid throughout the lifetime of the OrtKernelImpl instance.
+ * \param[in] prepacked_weight_cache May be NULL. If not NULL, the kernel may choose to share a packed weight by
+ * first storing it in the OrtSharedPrePackedWeightCache instance and then
+ * receiving the actual shared weight data in the call to
+ * OrtKernelImpl::SetSharedPrePackedWeight(). See the above description for
+ * "sharing mode".
+ * \param[out] is_packed Output parameter that the implementation sets to true if the kernel packed the tensor data.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Implementation of this function is optional. If not implemented (set to NULL), ORT assumes the kernel
+ * does not pre-pack weight data (i.e., `is_packed` defaults to false).
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(PrePackWeight, _In_ OrtKernelImpl* this_ptr, _In_ const OrtValue* tensor,
+ _In_ int input_index, _Inout_ OrtAllocator* allocator,
+ _In_opt_ OrtSharedPrePackedWeightCache* prepacked_weight_cache, _Out_ bool* is_packed);
+
+ /** \brief Optional function that receives data for a shared pre-packed weight from ORT.
+ *
+ * ORT calls this function after calling OrtKernelImpl::PrePackWeight for a specific `input_index` if:
+ * - OrtKernelImpl::PrePackWeight set the output parameter `is_packed` to true.
+ * - OrtKernelImpl::PrePackWeight stored weight data to share into the provided OrtSharedPrePackedWeightCache
+ * parameter (`prepacked_weight_cache`) via the API SharedPrePackedWeightCache_StoreWeightData.
+ *
+ * Refer to the description of the "sharing-mode" in the documentation for OrtKernelImpl::PrePackWeight().
+ *
+ * \note ORT will not call this function for an `input_index` that a previous call to
+ * OrtKernelImpl::PrePackWeight() did not elect to pre-pack and share.
+ *
+ * \note This function is based on the internal OpKernel::UseSharedPrePackedBuffers() virtual function used
+ * within ORT.
+ *
+ * \param[in] this_ptr The OrtKernelImpl instance.
+ * \param[in] buffer_data_ptrs An array of buffer data pointers that collectively hold the pre-packed data for a
+ * single shared weight. The buffers are provided in the same order and with the same
+ * contents (in a potentially different memory location) as the buffers
+ * passed into SharedPrePackedWeightCache_StoreWeightData() within the
+ * OrtKernelImpl::PrePackWeight() call for the same `input_index`.
+ * \param[in] buffer_data_sizes An array of buffer byte sizes, one per element in `buffer_data_ptrs`.
+ * \param[in] num_buffers The number of buffers used to store the data for the shared pre-packed weight.
+ * Specifies the number of elements in the `buffer_data_ptrs` and `buffer_data_sizes` arrays.
+ * \param[in] input_index The input index of the tensor in this kernel. This index identifies the identity of
+ * the weight.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Implementation of this function is generally optional. It is only required if OrtKernelImpl::PrePack()
+ * elects to share pre-packed weights.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(SetSharedPrePackedWeight, _In_ OrtKernelImpl* this_ptr,
+ _In_reads_(num_buffers) const void* const* buffer_data_ptrs,
+ _In_reads_(num_buffers) const size_t* buffer_data_sizes,
+ _In_ size_t num_buffers, _In_ int input_index);
+};
+
+/** \brief Type definition for a function that creates an OrtKernelImpl instance for an operator kernel.
+ *
+ * \param[in] kernel_create_func_state Opaque state initially provided by the EP that registered the kernel.
+ * Refer to OrtEpApi::KernelRegistry_AddKernel(). May be null.
+ * \param[in] info The OrtKernelInfo instance that provides access to the kernel's input and output characteristics.
+ * \param[out] kernel_out Output parameter set to the new OrtKernelImpl instance. On success, ownership of this
+ * OrtKernelImpl instance transfers to ORT, which will call OrtKernelImpl::Release() to
+ * release the instance when it is no longer used.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+typedef OrtStatus*(ORT_API_CALL* OrtKernelCreateFunc)(_In_ void* kernel_create_func_state,
+ _In_ const OrtKernelInfo* info,
+ _Outptr_result_maybenull_ OrtKernelImpl** kernel_out);
+
+struct OrtLoopKernelHelper;
+typedef struct OrtLoopKernelHelper OrtLoopKernelHelper;
+
+/**
+ * \brief Contains helper functions for a Loop OrtKernelImpl created via OrtEpApi::CreateLoopKernel.
+ * \since Version 1.24.
+ */
+struct OrtLoopKernelHelper {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ /** \brief Called by ORT to release the OrtLoopKernelHelper instance and its resources.
+ *
+ * \param[in] this_ptr The OrtLoopKernelHelper instance.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, Release, _In_ OrtLoopKernelHelper* this_ptr);
+
+ /** \brief Helper function that concatenates OrtValue instances from each loop iteration into a single
+ * pre-allocated output buffer.
+ *
+ * \note Implementing this function is required for all Loop opset versions.
+ *
+ * \param[in] this_ptr The OrtLoopKernelHelper instance.
+ * \param[in] stream_handle Optional native stream handle that enables asynchronous operations. May be NULL.
+ * \param[in] per_iteration_outputs Array of OrtValue instances from each iteration. All OrtValue elements have the
+ * same shape.
+ * \param[in] num_per_iteration_outputs The number of OrtValue* elements in the `per_iteration_outputs` array.
+ * \param[out] output The pre-allocated output buffer. Memory is allocated on the device for the EP running the
+ * Loop node.
+ * \param[in] output_size_in_bytes The size in bytes of the `output` buffer. It is guaranteed to be large enough
+ * to hold the concatenated data of each element in `per_iteration_outputs`.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(ConcatOutput, _In_ OrtLoopKernelHelper* this_ptr, _In_opt_ void* stream_handle,
+ _In_reads_(num_per_iteration_outputs) const OrtValue* const* per_iteration_outputs,
+ _In_ size_t num_per_iteration_outputs, _Out_writes_bytes_all_(output_size_in_bytes) void* output,
+ _In_ size_t output_size_in_bytes);
+};
+
+struct OrtScanKernelHelper;
+typedef struct OrtScanKernelHelper OrtScanKernelHelper;
+
+/**
+ * \brief Contains helper functions for a Scan OrtKernelImpl created via OrtEpApi::CreateScanKernel.
+ * \since Version 1.24.
+ */
+struct OrtScanKernelHelper {
+ uint32_t ort_version_supported; ///< Must be initialized to ORT_API_VERSION
+
+ /** \brief Called by ORT to release the OrtScanKernelHelper instance and its resources.
+ *
+ * \param[in] this_ptr The OrtScanKernelHelper instance.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(void, Release, _In_ OrtScanKernelHelper* this_ptr);
+
+ /** \brief Helper function that transposes an OrtValue instance during execution of a Scan kernel.
+ *
+ * \note Called for Scan (opset >= 9) when the 'scan_input_axes' or 'scan_output_axes' attributes contain
+ * non-zero values. Implementing this function is required for Scan opset versions >= 9.
+ *
+ * \param[in] this_ptr The OrtScanKernelHelper instance.
+ * \param[in] permutation An array of integers that defines how the input tensor's axes should be permuted.
+ * \param[in] num_permutation_elems The number of integer elements in the `permutation` array.
+ * \param[in] input The input OrtValue tensor to transpose.
+ * \param[in] stream An optional OrtSyncStream instance to be used for asynchronous operations. May be NULL.
+ * \param[out] output The pre-allocated output OrtValue instance into which to store the results of the
+ * transpose operation. Must not be released as it is owned by ORT.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(Transpose, _In_ OrtScanKernelHelper* this_ptr,
+ _In_reads_(num_permutation_elems) const size_t* permutation, _In_ size_t num_permutation_elems,
+ _In_ const OrtValue* input, _In_opt_ OrtSyncStream* stream, _Inout_ OrtValue* output);
+};
+
+/**
+ * \brief The OrtEpApi struct provides functions that are relevant to the implementation of an execution provider.
+ *
+ * \since Version 1.22.
+ */
+struct OrtEpApi {
+ /** \brief Create an OrtEpDevice for the EP and an OrtHardwareDevice.
+ * \param[in] ep_factory Execution provider factory that is creating the instance.
+ * \param[in] hardware_device Hardware device that the EP can utilize.
+ * \param[in] ep_metadata Optional OrtKeyValuePairs instance for execution provider metadata that may be used
+ * during execution provider selection and passed to CreateEp.
+ * ep_device will copy this instance and the user should call ReleaseKeyValuePairs.
+ * \param[in] ep_options Optional OrtKeyValuePairs instance for execution provider options that will be added
+ * to the Session configuration options if the execution provider is selected.
+ * ep_device will copy this instance and the user should call ReleaseKeyValuePairs.
+ * \param ep_device OrtExecutionDevice that is created.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateEpDevice, _In_ OrtEpFactory* ep_factory,
+ _In_ const OrtHardwareDevice* hardware_device,
+ _In_opt_ const OrtKeyValuePairs* ep_metadata,
+ _In_opt_ const OrtKeyValuePairs* ep_options,
+ _Out_ OrtEpDevice** ep_device);
+
+ ORT_CLASS_RELEASE(EpDevice);
+
+ /** \brief Specify nodes that are supported by an OrtEp and should be fused into one node.
+ *
+ * Because the nodes will be fused into one "fused node", there must not exist an unsupported node in
+ * a path between two of the provided nodes. Otherwise, the graph will become invalid.
+ *
+ * This function can be called multiple times. A subsequent call to this function will force the next set of
+ * nodes to be fused into a different node.
+ *
+ * \param[in] graph_support_info OrtEpGraphSupportInfo instance to which to add the supported nodes.
+ * \param[in] nodes Array of nodes supported by the EP that should be fused/compiled.
+ * \param[in] num_nodes The number of supported nodes.
+ * \param[in] node_fusion_options Optional node fusion options. Ignored if set to NULL.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(EpGraphSupportInfo_AddNodesToFuse, _In_ OrtEpGraphSupportInfo* graph_support_info,
+ _In_reads_(num_nodes) const OrtNode* const* nodes, _In_ size_t num_nodes,
+ _In_opt_ const OrtNodeFusionOptions* node_fusion_options);
+
+ /** \brief Specify a node that is supported by an OrtEp and should be run with a registered EP kernel.
+ *
+ * \param[in] graph_support_info OrtEpGraphSupportInfo instance to which to add the supported node.
+ * \param[in] node The supported OrtNode instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(EpGraphSupportInfo_AddSingleNode, _In_ OrtEpGraphSupportInfo* graph_support_info,
+ _In_ const OrtNode* node);
+
+ /** \brief Query a OrtNodeComputeContext for the name of the node that encapsulates the compiled/fused node.
+ *
+ * Used in OrtNodeComputeInfo::CreateComputeState().
+ *
+ * \param[in] context The OrtNodeComputeContext instance to query.
+ * \return The node's name.
+ *
+ * \note Returned string is owned by ORT and valid only while OrtNodeComputeInfo::CreateComputeState() is called.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const char*, NodeComputeContext_NodeName, _In_ const OrtNodeComputeContext* context);
+
+ /** \brief Register an allocator with the OrtEpDevice.
+ *
+ * This allows an EP to provide OrtMemoryInfo for DEFAULT and HOST_ACCESSIBLE memory type as needed.
+ * The registered values will be used in calls to OrtEpFactory::CreateAllocator to ensure the required allocator/s
+ * are available for EP usage.
+ *
+ * Multiple calls for the same entry type will replace a previous entry.
+ *
+ * Available entries:
+ * - OrtDeviceAllocator with type of OrtDeviceMemoryType_DEFAULT
+ * - OrtDeviceAllocator with type of OrtDeviceMemoryType_HOST_ACCESSIBLE
+ * - OrtReadOnlyAllocator with type of OrtDeviceMemoryType_DEFAULT
+ * - if provided this allocator will only be used to copy initializers to the device the EP uses.
+ * ORT will use the OrtDeviceAllocator if not provided.
+ *
+ * \param[in] ep_device The OrtEpDevice instance to register the OrtMemoryInfo with.
+ * \param[in] allocator_memory_info The OrtMemoryInfo information for the allocator.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(EpDevice_AddAllocatorInfo, _In_ OrtEpDevice* ep_device,
+ _In_ const OrtMemoryInfo* allocator_memory_info);
+
+ /** \brief Get the OrtMemoryDevice from an OrtMemoryInfo instance.
+ *
+ * This is required for OrtDataTransferImpl (which implements onnxruntime::IDataTransfer) where the OrtMemoryDevice
+ * is used in the CanCopy and CopyTensors functions.
+ *
+ * \param[in] memory_info The OrtMemoryInfo instance to get the memory device from.
+ * \return The OrtMemoryDevice associated with the OrtMemoryInfo instance.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const OrtMemoryDevice*, MemoryInfo_GetMemoryDevice, _In_ const OrtMemoryInfo* memory_info);
+
+ /** \brief Get the OrtMemoryDevice from an OrtValue instance if it contains a Tensor.
+ *
+ * \param[in] value The OrtValue instance to get the memory device from.
+ * \return Memory device if OrtValue contains a Tensor, nullptr otherwise.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const OrtMemoryDevice*, Value_GetMemoryDevice, _In_ const OrtValue* value);
+
+ /** \brief Compare two OrtMemoryDevice instances for equality.
+ *
+ * This is used to check if two memory devices are the same.
+ * Used to implement DataTransferImpl::CanCopy.
+ *
+ * \param[in] a The first OrtMemoryDevice instance to compare.
+ * \param[in] b The second OrtMemoryDevice instance to compare.
+ * \return True if the two OrtMemoryDevice instances are equal, false otherwise.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(bool, MemoryDevice_AreEqual, _In_ const OrtMemoryDevice* a, _In_ const OrtMemoryDevice* b);
+
+ /** \brief Get the OrtMemoryInfoDeviceType value from an OrtMemoryDevice instance.
+ *
+ * \param[in] memory_device OrtMemoryDevice instance.
+ * \return The OrtMemoryInfoDeviceType value.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(OrtMemoryInfoDeviceType, MemoryDevice_GetDeviceType, _In_ const OrtMemoryDevice* memory_device);
+
+ /** \brief Get the OrtDeviceMemoryType value from an OrtMemoryDevice instance.
+ *
+ * \param[in] memory_device OrtMemoryDevice instance.
+ * \return The OrtDeviceMemoryType value.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(OrtDeviceMemoryType, MemoryDevice_GetMemoryType, _In_ const OrtMemoryDevice* memory_device);
+
+ /** \brief Get the vendor ID from an OrtMemoryDevice instance.
+ *
+ * The vendor ID is used to identify the vendor of the device, and is typically set to the PCI vendor ID.
+ *
+ * If the device is not vendor specific (e.g. CPU memory) the vendor ID is set to 0.
+ *
+ * \param[in] memory_device OrtMemoryDevice instance.
+ * \return The vendor ID value.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(uint32_t, MemoryDevice_GetVendorId, _In_ const OrtMemoryDevice* memory_device);
+
+ /** \brief Get the device ID from an OrtMemoryDevice instance.
+ *
+ * \param[in] memory_device OrtMemoryDevice instance.
+ * \return The device ID.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(uint32_t, MemoryDevice_GetDeviceId, _In_ const OrtMemoryDevice* memory_device);
+
+ /** \brief Get the OrtSyncStreamImpl associated with an OrtSyncStream instance.
+ *
+ * This allows an the plugin library to connect its OrtSyncStreamImpl instance with an OrtSyncStream if needed.
+ *
+ * \param[in] stream The OrtSyncStream instance to find an OrtSyncStreamImpl for.
+ * \return The associated OrtSyncStreamImpl if found. nullptr otherwise.
+ *
+ * \since Version 1.23.
+ *
+ * \remarks There should always be an OrtSyncStreamImpl associated with an OrtSyncStream instance that the EP gets.
+ */
+ ORT_API_T(const OrtSyncStreamImpl*, SyncStream_GetImpl, _In_ const OrtSyncStream* stream);
+
+ /** \brief Get the current sync ID for a stream.
+ *
+ * \param[in] stream The OrtSyncStream to get the sync ID for.
+ * \return Current sync ID.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(uint64_t, SyncStream_GetSyncId, _In_ const OrtSyncStream* stream);
+
+ /** \brief Get the sync ID for the last time the consumer_stream waited on the producer_stream.
+ *
+ * When two streams are synchronized, the sync id represents the event used in that synchronization.
+ *
+ * \param[in] producer_stream The OrtSyncStream that produced the data.
+ * \param[in] consumer_stream The OrtSyncStream that waited on the producer_stream.
+ * \return ID for last sync. 0 if no sync has occurred between the two streams.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(uint64_t, GetSyncIdForLastWaitOnSyncStream,
+ _In_ const OrtSyncStream* producer_stream, _In_ const OrtSyncStream* consumer_stream);
+
+ /** \brief Create an OrtHardwareDevice.
+ *
+ * \note Called within OrtEpFactory::GetSupportedDevices to create a new hardware device (e.g., virtual).
+ *
+ * \param[in] type The hardware device type.
+ * \param[in] vendor_id The hardware device's vendor identifier.
+ * \param[in] device_id The hardware device's identifier.
+ * \param[in] vendor_name The hardware device's vendor name as a null-terminated string. Copied by ORT.
+ * \param[in] metadata Optional OrtKeyValuePairs instance for hardware device metadata that may be queried by
+ * applications via OrtApi::GetEpDevices().
+ * Refer to onnxruntime_ep_device_ep_metadata_keys.h for common OrtHardwareDevice metadata keys.
+ * \param[out] hardware_device Output parameter set to the new OrtHardwareDevice instance that is created.
+ * Must be release with ReleaseHardwareDevice().
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateHardwareDevice, _In_ OrtHardwareDeviceType type,
+ _In_ uint32_t vendor_id,
+ _In_ uint32_t device_id,
+ _In_ const char* vendor_name,
+ _In_opt_ const OrtKeyValuePairs* metadata,
+ _Out_ OrtHardwareDevice** hardware_device);
+
+ ORT_CLASS_RELEASE(HardwareDevice);
+
+ /** \brief Creates an empty kernel registry. A kernel registry contains kernel creation information for
+ * every operator kernel supported by an EP.
+ *
+ * \remarks Refer to OrtEp::GetKernelRegistry, which returns an EP's kernel registry to ORT.
+ *
+ * \param[out] kernel_registry Output parameter set to the new OrtKernelRegistry instance.
+ * Must be released with OrtEpApi::ReleaseKernelRegistry.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateKernelRegistry, _Outptr_ OrtKernelRegistry** kernel_registry);
+
+ ORT_CLASS_RELEASE(KernelRegistry);
+
+ /** \brief Adds kernel creation information for a supported operator kernel to the given kernel registry.
+ *
+ * \remarks Refer to OrtEp::GetKernelRegistry, which returns an EP's kernel registry to ORT.
+ *
+ * \param[in] kernel_registry The OrtKernelRegistry instance.
+ * \param[in] kernel_def The kernel definition, which includes operator type, version, EP name, type constraints, etc.
+ * \param[in] kernel_create_func Function that creates an instance of the operator kernel as a OrtKernelImpl instance.
+ * \param[in] kernel_create_func_state Custom state passed to the kernel creation function. Can be null.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelRegistry_AddKernel, _In_ OrtKernelRegistry* kernel_registry,
+ _In_ const OrtKernelDef* kernel_def, _In_ OrtKernelCreateFunc kernel_create_func,
+ _In_ void* kernel_create_func_state);
+
+ /** \brief Creates a kernel definition builder used to create instances of OrtKernelDef.
+ *
+ * \param[out] kernel_def_builder_out Output parameter set to the new OrtKernelDefBuilder instance.
+ * Must be released with OrtEpApi::ReleaseKernelDefBuilder().
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateKernelDefBuilder, _Outptr_ OrtKernelDefBuilder** kernel_def_builder_out);
+
+ ORT_CLASS_RELEASE(KernelDefBuilder);
+
+ /** \brief Sets the kernel's operator type.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] op_type A null-terminated string representing the operator type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetOperatorType, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ const char* op_type);
+
+ /** \brief Sets the kernel's domain.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] domain A null-terminated string representing the operator's domain.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetDomain, _In_ OrtKernelDefBuilder* kernel_def_builder, _In_ const char* domain);
+
+ /** \brief Sets the kernel's opset version range that is supported.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] since_version_start The starting opset version that is supported.
+ * \param[in] since_version_end The ending opset version (inclusive) that is supported.
+ * Can be set equal to the starting version to indicate that only one
+ * version is supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetSinceVersion, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ int since_version_start, _In_ int since_version_end);
+
+ /** \brief Sets the name of the kernel's intended execution provider.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] ep_name A null-terminated string representing the execution provider's name.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetExecutionProvider, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ const char* ep_name);
+
+ /** \brief Sets the memory type for a kernel input.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] input_index The index of the input.
+ * \param[in] mem_type The input's memory type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetInputMemType, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ size_t input_index, _In_ OrtMemType mem_type);
+
+ /** \brief Sets the memory type for a kernel output.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] output_index The index of the output.
+ * \param[in] mem_type The output's memory type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_SetOutputMemType, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ size_t output_index, _In_ OrtMemType mem_type);
+
+ /** \brief Adds type constraints for a kernel argument represented as a string (e.g., "T").
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] arg_name A null-terminated string representing the argument to constrain (e.g., "T").
+ * \param[in] types Array of OrtDataType instances representing allowed types for the argument.
+ * Must contain `num_types` elements.
+ * \param[in] num_types The number of OrtDataType elements in the `types` array.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_AddTypeConstraint, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_ const char* arg_name, _In_reads_(num_types) const OrtDataType* const* types,
+ _In_ size_t num_types);
+
+ /** \brief Adds aliases for the given input and output pairs.
+ *
+ * \note Used for operators like Identity and Reshape to allow ORT to reuse the input buffer for the output
+ * without modification.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] input_indices Array of input indices. Array must contain `num_io_indices` elements.
+ * \param[in] output_indices Array of output indices. Each output index is aliased with a corresponding
+ * input index in `input_indices`. Array must contain `num_io_indices` elements.
+ * \param[in] num_io_indices The number of input/output index pairs to alias.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_AddInputOutputAliases, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_reads_(num_io_indices) int const* input_indices,
+ _In_reads_(num_io_indices) int const* output_indices,
+ _In_ size_t num_io_indices);
+
+ /** \brief Adds mutable aliases for the given input and output pairs.
+ *
+ * \note Allows ORT to reuse and *modify* an input buffer (in-place) for the output buffer.
+ * This is also known as "MayInplace" within the ORT codebase.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[in] input_indices Array of input indices. Array must contain `num_io_indices` elements.
+ * \param[in] output_indices Array of output indices. Each output index is aliased with a corresponding
+ * input index in `input_indices`. Array must contain `num_io_indices` elements.
+ * \param[in] num_io_indices The number of input/output index pairs to alias.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_AddInputOutputMutableAliases, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _In_reads_(num_io_indices) int const* input_indices,
+ _In_reads_(num_io_indices) int const* output_indices,
+ _In_ size_t num_io_indices);
+
+ /** \brief Creates a OrtKernelDef instance from the given kernel definition builder.
+ *
+ * \param[in] kernel_def_builder The OrtKernelDefBuilder instance.
+ * \param[out] kernel_def_out The new OrtKernelDef instance.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDefBuilder_Build, _In_ OrtKernelDefBuilder* kernel_def_builder,
+ _Outptr_ OrtKernelDef** kernel_def_out);
+
+ ORT_CLASS_RELEASE(KernelDef);
+
+ /** \brief Returns the operator type from the kernel definition.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \return A null-terminated string representing the operator type.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(const char*, KernelDef_GetOperatorType, _In_ const OrtKernelDef* kernel_def);
+
+ /** \brief Returns the operator's domain from the kernel definition.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \return A null-terminated string representing the operator's domain.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(const char*, KernelDef_GetDomain, _In_ const OrtKernelDef* kernel_def);
+
+ /** \brief Gets the kernel's opset version range that is supported.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \param[out] start_version Output parameter set to the starting opset version that is supported.
+ * \param[out] end_version Output parameter set to the ending opset version (inclusive) that is supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDef_GetSinceVersion, _In_ const OrtKernelDef* kernel_def,
+ _Out_ int* start_version, _Out_ int* end_version);
+
+ /** \brief Returns the name of the kernel's intended execution provider.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \return A null-terminated string representing the name of the execution provider.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API_T(const char*, KernelDef_GetExecutionProvider, _In_ const OrtKernelDef* kernel_def);
+
+ /** \brief Gets the memory type for a kernel input.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \param[in] input_index The index of the input.
+ * \param[out] mem_type Output parameter set to the input's memory type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDef_GetInputMemType, _In_ const OrtKernelDef* kernel_def,
+ _In_ size_t input_index, _Out_ OrtMemType* mem_type);
+
+ /** \brief Gets the memory type for a kernel output.
+ *
+ * \param[in] kernel_def The OrtKernelDef instance.
+ * \param[in] output_index The index of the output.
+ * \param[out] mem_type Output parameter set to the output's memory type.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(KernelDef_GetOutputMemType, _In_ const OrtKernelDef* kernel_def,
+ _In_ size_t output_index, _Out_ OrtMemType* mem_type);
+
+ /** \brief Gets the OrtDataType that represents the data type for a tensor of the given element type.
+ *
+ * \param[in] elem_type The tensor's element type.
+ * \param[out] out Output parameter set to the OrtDataType. Owned by ORT and must not be released.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetTensorDataType, _In_ ONNXTensorElementDataType elem_type,
+ _Outptr_ const OrtDataType** out);
+
+ /** \brief Gets the kernel definition for a given node, if any exists for the calling execution provider.
+ *
+ * Used within OrtEp::GetCapability() to get the registered kernel definition for the given node.
+ * The kernel definition is set to NULL if there is no registered kernel definition for the node
+ * and execution provider.
+ *
+ * \param[in] graph_support_info The OrtEpGraphSupportInfo instance to query.
+ * \param[in] node The node for which to look up a kernel definition.
+ * \param[out] out_kernel_def Output parameter set to the OrtKernelDef or NULL.
+ * Owned by ORT and must not be released.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(EpGraphSupportInfo_LookUpKernel, _In_ OrtEpGraphSupportInfo* graph_support_info,
+ _In_ const OrtNode* node, _Outptr_result_maybenull_ const OrtKernelDef** out_kernel_def);
+
+ /** \brief Sets one or more data buffers that collectively hold the pre-packed data for a single shared weight.
+ *
+ * \note Used within the implementation of OrtKernelImpl::PrePackWeight() when the kernel wants to share pre-packed
+ * weight data with other kernels. The buffer data MUST be allocated with the OrtAllocator provided to
+ * OrtKernelImpl::PrePack.
+ *
+ * \note Ownership of weight data transfers to the OrtSharedPrePackedWeightCache instance on success.
+ * If this function returns an error status, the caller retains ownership of the weight data.
+ *
+ * \note Subsequent calls with the same OrtSharedPrePackedWeightCache instance release and replace the old data.
+ *
+ * \param[in] prepacked_weight_cache The OrtSharedPrePackedWeightCache instance.
+ * \param[in] buffer_data_ptrs An array of buffer data pointers that collectively hold the pre-packed data for a
+ * single shared weight. Note that sometimes a single weight may have multiple pre-packed
+ * buffers and it is up to the kernel implementation to determine how to split the data
+ * into multiple buffers (if desired).
+ * \param[in] buffer_data_sizes An array of buffer byte sizes, one per element in `buffer_data_ptrs`.
+ * \param[in] num_buffers The number of buffers used to store the data for the shared pre-packed weight.
+ * Specifies the number of elements in the `buffer_data_ptrs` and `buffer_data_sizes` arrays.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(SharedPrePackedWeightCache_StoreWeightData,
+ _In_ OrtSharedPrePackedWeightCache* prepacked_weight_cache,
+ _In_reads_(num_buffers) void** buffer_data_ptrs, _In_reads_(num_buffers) size_t* buffer_data_sizes,
+ _In_ size_t num_buffers);
+
+ /** \brief Get the OrtEp instance to which the node is assigned from the OrtKernelInfo.
+ *
+ * \note Used within OrtKernelImpl implementations to obtain a reference to the OrtEp.
+ *
+ * \param[in] info The ::OrtKernelInfo instance.
+ * \param[out] ep Output parameter set to the OrtEp instance associated with the OrtKernelInfo.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(KernelInfo_GetEp, _In_ const OrtKernelInfo* info, _Outptr_ const OrtEp** ep);
+
+ /** \brief Set the details of an OrtDeviceEpIncompatibilityDetails instance.
+ *
+ * Used by execution provider factories to set incompatibility details in their
+ * GetHardwareDeviceIncompatibilityDetails implementation. ORT creates and initializes the object
+ * before passing it to the EP, so calling this function is optional. The EP uses this function
+ * to set incompatibility information when the device is not compatible.
+ *
+ * \param[in,out] details The OrtDeviceEpIncompatibilityDetails instance to update.
+ * \param[in] reasons_bitmask Bitmask of OrtDeviceEpIncompatibilityReason values. (0 = no incompatibility).
+ * \param[in] error_code Optional EP-specific error code (0 = no error).
+ * \param[in] notes Optional human-readable notes. Can be null.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(DeviceEpIncompatibilityDetails_SetDetails, _Inout_ OrtDeviceEpIncompatibilityDetails* details,
+ _In_ uint32_t reasons_bitmask,
+ _In_ int32_t error_code,
+ _In_opt_z_ const char* notes);
+
+ /** \brief Creates an OrtKernelImpl instance for an If operator.
+ *
+ * Control flow operators require access to ORT session internals to orchestrate subgraph operations.
+ * This function allows an EP to create a properly configured OrtKernelImpl with access to ORT internals that
+ * the EP can add to its kernel registry.
+ *
+ * An EP is required to create an OrtKernelDef that keeps input[0] ('cond') on the CPU (i.e., OrtMemTypeCPUInput)
+ * as this input is used by CPU logic. The output should remain on the device (i.e., OrtMemTypeDefault), which is
+ * the default setting, to avoid copying to/from CPU.
+ *
+ * Example kernel definition (CXX API):
+ * Ort::KernelDef kernel_def = Ort::KernelDefBuilder()
+ * .SetDomain("").SetOperatorType("If").SetSinceVersion(21, 22)
+ * .SetExecutionProvider("MyEp")
+ * .SetInputMemType(0, OrtMemTypeCPUInput) // 'cond' on CPU
+ * .SetOutputMemType(0, OrtMemTypeDefault) // output on EP device
+ * .AddTypeConstraint("B", ...)
+ * .AddTypeConstraint("V", ...).Build();
+ *
+ * \param[in] kernel_info The ::OrtKernelInfo instance for an If node. This function returns error ORT_FAIL
+ * if the opset version specified by `kernel_info` is unsupported.
+ * \param[out] kernel_out Output parameter set to the OrtKernelImpl instance for the If node.
+ * Must be released via ::ReleaseKernelImpl, unless ownership is transferred
+ * to ORT (see OrtKernelCreateFunc and ::KernelRegistry_AddKernel()).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(CreateIfKernel, _In_ const OrtKernelInfo* kernel_info, _Outptr_ OrtKernelImpl** kernel_out);
+
+ /** \brief Creates an OrtKernelImpl instance for a Loop operator.
+ *
+ * Control flow operators require access to ORT session internals to orchestrate subgraph operations.
+ * This function allows an EP to create a properly configured OrtKernelImpl with access to ORT internals that
+ * the EP can add to its kernel registry.
+ *
+ * An EP is required to create an OrtKernelDef that keeps input[0] ('M') and input[1] ('cond') on the CPU
+ * (i.e., OrtMemTypeCPUInput) as these inputs are used by CPU logic. Input[2] ('v_initial') and the output should
+ * remain on the device (i.e., OrtMemTypeDefault), which is the default setting, to avoid copying to/from CPU.
+ *
+ * Example kernel definition (CXX API):
+ * Ort::KernelDef kernel_def = Ort::KernelDefBuilder()
+ * .SetDomain("").SetOperatorType("Loop").SetSinceVersion(21, 22)
+ * .SetExecutionProvider("MyEp")
+ * .SetInputMemType(0, OrtMemTypeCPUInput) // 'M' on CPU
+ * .SetInputMemType(1, OrtMemTypeCPUInput) // 'cond' on CPU
+ * .SetInputMemType(2, OrtMemTypeDefault) // 'v_initial' on EP device
+ * .SetOutputMemType(0, OrtMemTypeDefault) // output on EP device
+ * .AddTypeConstraint("I", ...)
+ * .AddTypeConstraint("B", ...)
+ * .AddTypeConstraint("V", ...).Build();
+ *
+ * \param[in] kernel_info The ::OrtKernelInfo instance for a Loop node. This function returns error ORT_FAIL
+ * if the opset version specified by `kernel_info` is unsupported.
+ * \param[in] helper A OrtLoopKernelHelper instance that contains helper functions that ORT calls during kernel
+ * execution to operate on tensors allocated with the EP's device memory.
+ * ORT will call OrtLoopKernelHelper::Release() to release the helper and its resources.
+ * \param[out] kernel_out Output parameter set to the OrtKernelImpl instance for the Loop node.
+ * Must be released via ::ReleaseKernelImpl, unless ownership is transferred
+ * to ORT (see OrtKernelCreateFunc and ::KernelRegistry_AddKernel()).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(CreateLoopKernel, _In_ const OrtKernelInfo* kernel_info, _In_ OrtLoopKernelHelper* helper,
+ _Outptr_ OrtKernelImpl** kernel_out);
+
+ /** \brief Creates an OrtKernelImpl instance for a Scan operator. Does not support opset versions older than 9.
+ *
+ * Control flow operators require access to ORT session internals to orchestrate subgraph operations.
+ * This function allows an EP to create a properly configured OrtKernelImpl with access to ORT internals that
+ * the EP can add to its kernel registry.
+ *
+ * It is recommended that an EP create an OrtKernelDef that keeps the inputs and outputs on the EP's
+ * device (i.e., OrtMemTypeDefault), which is the default setting, to avoid copying to/from CPU.
+ *
+ * Example kernel definition (CXX API):
+ * Ort::KernelDef kernel_def = Ort::KernelDefBuilder()
+ * .SetDomain("").SetOperatorType("Scan").SetSinceVersion(21, 22)
+ * .SetExecutionProvider("MyEp")
+ * .SetInputMemType(0, OrtMemTypeDefault) // input[0] on EP device
+ * .SetOutputMemType(0, OrtMemTypeDefault) // output[0] on EP device
+ * .AddTypeConstraint("V", ...).Build();
+ *
+ * \param[in] kernel_info The ::OrtKernelInfo instance for a Scan node. This function returns error ORT_FAIL
+ * if the opset version specified by `kernel_info` is unsupported.
+ * \param[in] helper A OrtScanKernelHelper instance that contains helper functions that ORT calls during kernel
+ * execution to operate on tensors allocated with the EP's device memory.
+ * ORT will call OrtScanKernelHelper::Release() to release the helper and its resources.
+ * \param[out] kernel_out Output parameter set to the OrtKernelImpl instance for the Scan node.
+ * Must be released via ::ReleaseKernelImpl, unless ownership is transferred
+ * to ORT (see OrtKernelCreateFunc and ::KernelRegistry_AddKernel()).
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(CreateScanKernel, _In_ const OrtKernelInfo* kernel_info, _In_ OrtScanKernelHelper* helper,
+ _Outptr_ OrtKernelImpl** kernel_out);
+
+ ORT_CLASS_RELEASE(KernelImpl);
+
+ /** \brief Gets a new OrtKeyValuePairs instance containing a copy of all configuration entries set on the environment.
+ *
+ * \note An application provides environment-level configuration options for execution provider libraries by
+ * using keys with the prefix 'ep_factory.\\<ep_name\\>.'. Ex: the key 'ep_factory.my_ep.some_ep_key' represents
+ * a key named 'some_ep_key' that is meant to be consumed by an execution provider named 'my_ep'. Refer to
+ * the specific execution provider's documentation for valid keys and values.
+ *
+ * \note Refer to onnxruntime_env_config_keys.h for common configuration entry keys and their supported values.
+ *
+ * \param[out] config_entries Output parameter set to the OrtKeyValuePairs instance containing all configuration entries.
+ * Must be released via OrtApi::ReleaseKeyValuePairs.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ * \since Version 1.24
+ */
+ ORT_API2_STATUS(GetEnvConfigEntries, _Outptr_ OrtKeyValuePairs** config_entries);
+};
+
+/**
+ * \brief The data layout type.
+ *
+ * EPs may specify a preferred data layout type. ORT's default layout type is OrtEpDataLayout_NCHW, or
+ * OrtEpDataLayout_Default.
+ *
+ * \since Version 1.23.
+ */
+typedef enum OrtEpDataLayout {
+ OrtEpDataLayout_NCHW = 0,
+ OrtEpDataLayout_NHWC,
+
+ OrtEpDataLayout_Default = OrtEpDataLayout_NCHW,
+} OrtEpDataLayout;
+
+/**
+ * \brief The OrtEp struct provides functions to implement for an execution provider.
+ * \since Version 1.22.
+ */
+struct OrtEp {
+ /** \brief The ONNX Runtime version the execution provider was compiled with.
+ *
+ * Implementation should set to ORT_API_VERSION.
+ * ORT will use this to ensure it does not call functions that were not available when the library was compiled.
+ *
+ * \since Version 1.22.
+ */
+ uint32_t ort_version_supported;
+
+ /** \brief Get the execution provider name.
+ *
+ * The returned string should be a null-terminated, UTF-8 encoded string. ORT will copy it.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \return The execution provider name.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API_T(const char*, GetName, _In_ const OrtEp* this_ptr);
+
+ /** \brief Get information about the nodes supported by the OrtEp instance.
+ *
+ * IMPORTANT: This is not the final version of this API function. This is currently experimental but will
+ * be stabilized by the ONNX Runtime 1.23 release.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] graph The OrtGraph instance for which to populate node support. The OrtGraph could be a nested subgraph
+ * contained by a node (e.g., an If or Loop node). ONNX Runtime calls this function separately
+ * for each nested subgraph.
+ * \param[inout] graph_support_info OrtEpGraphSupportInfo instance that the implementer must fill out in order to
+ * specify the supported nodes.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(GetCapability, _In_ OrtEp* this_ptr, _In_ const OrtGraph* graph,
+ _Inout_ OrtEpGraphSupportInfo* graph_support_info);
+
+ /** \brief Compile OrtGraph instances assigned to the OrtEp. Implementer must set a OrtNodeComputeInfo instance
+ * for each OrtGraph in order to define its computation function.
+ *
+ * If the session is configured to generate a pre-compiled model, the execution provider must return EPContext nodes,
+ * as OrtNode instances, that ONNX Runtime uses to create a pre-compiled model, known as an "EPContext model".
+ * An EPContext model contains EPContext nodes. Each EPContext node encapsulates the pre-compiled binary data for a
+ * OrtGraph compiled for a specific execution provider. For more details about the EPContext design, refer to:
+ * \htmlonly
+ * <a href="https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html">EPContext design document.</a>
+ * \endhtmlonly
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] graphs Array of `count` OrtGraph instances to compile. Each graph contains only the nodes for
+ * which the execution provider indicated support. Nested subgraphs contained by a
+ * node, such as an If or Loop, have separate OrtGraph instances.
+ * \param[in] fused_nodes Array of `count` fused nodes that will replace the compiled graphs.
+ * Each fused node is an OrtNode initialized with the intended fused node name and
+ * input/output information.
+ * \param[in] count The number of OrtGraph instances to compile.
+ * \param[out] node_compute_infos Array of `count` OrtNodeComputeInfo instances that define each OrtGraph instance's
+ * computation function. The implementer allocates the OrtNodeComputeInfo instances.
+ * ORT calls ReleaseNodeComputeInfos() to release multiple instances in a batch.
+ * \param[out] ep_context_nodes Output array of `count` OrtNode instances, each representing an EPContext
+ * node for a compiled OrtGraph. The execution provider must use
+ * OrtModelEditorApi::CreateNode to create the OrtNode instances. ONNX Runtime takes
+ * ownership of the OrtNode instances, so the execution provider must NOT call
+ * OrtApi::ReleaseNode. Should be ignored if the session is not configured to generate an
+ * EPContext model.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Do NOT cache the provided OrtGraph instances in any of the OrtNodeComputeInfo functions because the
+ * graphs are only valid for the duration of the call to Compile. Any graph/node/input/output
+ * names that are needed by the OrtNodeComputeInfo functions must be copied and stored by the OrtEp.
+ *
+ * \note As of version 1.24, implementation of this function is optional if the EP does not compile nodes and
+ * uses a kernel registry instead.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(Compile, _In_ OrtEp* this_ptr, _In_ const OrtGraph** graphs,
+ _In_ const OrtNode** fused_nodes, _In_ size_t count,
+ _Out_writes_all_(count) OrtNodeComputeInfo** node_compute_infos,
+ _Out_writes_(count) OrtNode** ep_context_nodes);
+
+ /** \brief Release OrtNodeComputeInfo instances.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[inout] node_compute_infos The OrtNodeComputeInfo instances to release.
+ * \param[in] num_node_compute_infos The number of OrtNodeComputeInfo instances.
+ *
+ * \note As of version 1.24, implementation of this function is optional if the EP does not compile nodes and
+ * uses a kernel registry instead.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void, ReleaseNodeComputeInfos, _In_ OrtEp* this_ptr,
+ OrtNodeComputeInfo** node_compute_infos,
+ _In_ size_t num_node_compute_infos);
+
+ /** \brief Get the EP's preferred data layout.
+ *
+ * \note Implementation of this function is optional.
+ * If not implemented, ORT will assume that this EP prefers the data layout `OrtEpDataLayout::NCHW`.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[out] preferred_data_layout The EP's preferred data layout.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(GetPreferredDataLayout, _In_ OrtEp* this_ptr, _Out_ OrtEpDataLayout* preferred_data_layout);
+
+ /** \brief Given an op with domain `domain` and type `op_type`, determine whether an associated node's data layout
+ * should be converted to `target_data_layout`.
+ * If the EP prefers a non-default data layout (see `GetPreferredDataLayout()`), this function will be called
+ * during layout transformation with `target_data_layout` set to the EP's preferred data layout.
+ *
+ * \note Implementation of this function is optional.
+ * If an EP prefers a non-default data layout, it may implement this to customize the specific op data layout
+ * preferences at a finer granularity.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] domain The op domain. An empty string means the ONNX domain.
+ * \param[in] op_type The op type.
+ * \param[in] target_data_layout The target data layout.
+ * \param[out] should_convert Whether the associated node's data layout should be converted to `target_data_layout`.
+ * If greater than 0, convert.
+ * If 0, don't convert.
+ * Otherwise, if less than 0, leave the decision to ORT.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ShouldConvertDataLayoutForOp, _In_ OrtEp* this_ptr,
+ _In_z_ const char* domain, _In_z_ const char* op_type,
+ _In_ OrtEpDataLayout target_data_layout,
+ _Outptr_ int* should_convert);
+
+ /** \brief Set dynamic options on this EP.
+ *
+ * Dynamic options can be set by the user at any time after session creation with `OrtApi::SetEpDynamicOptions()`.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] option_keys The dynamic option keys.
+ * \param[in] option_values The dynamic option values.
+ * \param[in] num_options The number of dynamic options.
+ *
+ * \note Implementation of this function is optional.
+ * An EP should only implement this if it needs to handle any dynamic options.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(SetDynamicOptions, _In_ OrtEp* this_ptr,
+ _In_reads_(num_options) const char* const* option_keys,
+ _In_reads_(num_options) const char* const* option_values,
+ _In_ size_t num_options);
+
+ /** \brief Called by ORT to notify the EP of the start of a run.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] run_options The run options for this run.
+ *
+ * \note Implementation of this function is optional.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OnRunStart, _In_ OrtEp* this_ptr, _In_ const OrtRunOptions* run_options);
+
+ /** \brief Called by ORT to notify the EP of the end of a run.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] run_options The run options for this run.
+ * \param[in] sync_stream Whether any associated stream should be synchronized during this call.
+ * Only applicable if there is such a stream.
+ *
+ * \note Implementation of this function is optional.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(OnRunEnd, _In_ OrtEp* this_ptr, _In_ const OrtRunOptions* run_options, _In_ bool sync_stream);
+
+ /** \brief Create an OrtAllocator for the given OrtMemoryInfo for an OrtSession.
+ *
+ * The OrtMemoryInfo instance will match one of the values set in the OrtEpDevice using EpDevice_AddAllocatorInfo.
+ * Any allocator specific options should be read from the session options.
+ *
+ * If nullptr OrtEpFactory::CreateAllocator will be used.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] memory_info The OrtMemoryInfo to create the allocator for. May be nullptr.
+ * \param[out] allocator The created OrtAllocator instance. Set to nullptr if the default CPU allocator is used.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateAllocator, _In_ OrtEp* this_ptr,
+ _In_ const OrtMemoryInfo* memory_info,
+ _Outptr_result_maybenull_ OrtAllocator** allocator);
+
+ /** \brief Create a synchronization stream for the given memory device for an OrtSession.
+ *
+ * This is used to create a synchronization stream for the execution provider and is used to synchronize
+ * operations on the device during model execution.
+ * Any stream specific options should be read from the session options.
+ *
+ * If nullptr OrtEpFactory::CreateSyncStreamForDevice will be used.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] memory_device The OrtMemoryDevice to create the synchronization stream for.
+ * \param[out] stream The created OrtSyncStreamImpl instance. nullptr if the execution provider is not stream aware.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateSyncStreamForDevice, _In_ OrtEp* this_ptr,
+ _In_ const OrtMemoryDevice* memory_device,
+ _Outptr_ OrtSyncStreamImpl** stream);
+
+ /** \brief Get a string with details about the EP stack used to produce a compiled model.
+ *
+ * This function gets a compatibility information string that contains details about the execution provider
+ * used to compile a given model. This string can later be used with ValidateCompiledModelCompatibilityInfo
+ * to determine if a compiled model is compatible with the EP.
+ *
+ * The returned string should be a null-terminated, UTF-8 encoded string. ORT will copy it.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[in] graph The OrtGraph instance for which to generate compatibility information.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const char*, GetCompiledModelCompatibilityInfo, _In_ OrtEp* this_ptr,
+ _In_ const OrtGraph* graph);
+
+ /** \brief Gets the execution provider's kernel registry, if any.
+ *
+ * A kernel registry contains kernel creation information for operator kernels supported by an EP.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[out] kernel_registry Output parameter set to the EP's kernel registry, which must remain valid throughout
+ * the lifetime of the EP. Can be NULL if the EP doesn't use a kernel registry.
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Implementation of this function is optional. If set to NULL, ORT assumes the EP compiles nodes.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetKernelRegistry, _In_ OrtEp* this_ptr,
+ _Outptr_result_maybenull_ const OrtKernelRegistry** kernel_registry);
+
+ /** \brief Gets whether the execution provider supports concurrent run calls made on the session.
+ *
+ * \param[in] this_ptr The OrtEp instance.
+ * \param[out] is_supported Whether concurrent runs are supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Implementation of this function is optional and it may be set to NULL.
+ * If not implemented, ORT assumes that concurrent runs are supported.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(IsConcurrentRunSupported, _In_ OrtEp* this_ptr, _Outptr_ bool* is_supported);
+};
+
+/** \brief The function signature that ORT will call to create OrtEpFactory instances.
+ *
+ * This must be available in a function called 'CreateEpFactories' in the execution provider library.
+ *
+ * \param[in] registered_name The name the execution library is registered with by RegisterExecutionProviderLibrary
+ * \param[in] ort_api_base The OrtApiBase instance that is used by the factory to get the OrtApi instance for the
+ * version of ORT that the library was compiled against.
+ * \param[in] default_logger The default ORT logger that can be used for logging outside of an inference session.
+ * \param[in,out] factories The implementation should create and add OrtEpFactory instances to this
+ * pre-allocated array.
+ * i.e. usage is `factories[0] = new MyEpFactory();`
+ * \param[in] max_factories The maximum number of OrtEpFactory instances that can be added to `factories`.
+ * Current default is to allow 4 factories. This can be increased in the future if needed.
+ * \param[out] num_factories The number of OrtEpFactory instances created by the factory and added to `factories`.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+typedef OrtStatus* (*CreateEpApiFactoriesFn)(_In_ const char* registered_name, _In_ const OrtApiBase* ort_api_base,
+ _In_ const OrtLogger* default_logger,
+ _Inout_ OrtEpFactory** factories, _In_ size_t max_factories,
+ _Out_ size_t* num_factories);
+
+/** \brief The function signature that ORT will call to release an OrtEpFactory instance.
+ *
+ * This must be available in a function called 'ReleaseEpFactory' in the execution provider library.
+ *
+ * \param[in] factory The OrtEpFactory instance to release.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+typedef OrtStatus* (*ReleaseEpApiFactoryFn)(_In_ OrtEpFactory* factory);
+
+/**
+ * \brief The OrtEpFactory provides functions to create and manage execution providers.
+ * \since Version 1.22.
+ */
+struct OrtEpFactory {
+ /** \brief The ONNX Runtime version the execution provider was compiled with.
+ *
+ * Implementation should set to ORT_API_VERSION.
+ * ORT will use this to ensure it does not call functions that were not available when the library was compiled.
+ *
+ * \since Version 1.22.
+ */
+ uint32_t ort_version_supported;
+
+ /** \brief Get the name of the execution provider that the factory creates.
+ *
+ * The returned string should be a null-terminated, UTF-8 encoded string. ORT will copy it.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \return The name of the execution provider the factory creates.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API_T(const char*, GetName, const OrtEpFactory* this_ptr);
+
+ /** \brief Get the name of vendor who owns the execution provider that the factory creates.
+ *
+ * The returned string should be a null-terminated, UTF-8 encoded string. ORT will copy it.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \return vendor The vendor name of the execution provider the factory creates.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API_T(const char*, GetVendor, const OrtEpFactory* this_ptr); // return EP vendor
+
+ /** \brief Get information from the execution provider about OrtHardwareDevice support.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * Non-const as the factory is passed through to the CreateEp call via the OrtEpDevice.
+ * \param[in] devices The OrtHardwareDevice instances that are available.
+ * \param[in] num_devices The number of OrtHardwareDevice instances.
+ * \param[out] ep_devices OrtEpDevice instances for each OrtHardwareDevice that the EP can use.
+ * The implementation should call OrtEpApi::CreateEpDevice to create, and add the OrtEpDevice
+ * instances to this pre-allocated array. ORT will take ownership of the values returned.
+ * i.e. usage is `ep_devices[0] = <ptr to OrtEpDevice created with OrtEpApi::CreateEpDevice>;`
+ * \param[in] max_ep_devices The maximum number of OrtEpDevices that can be added to ep_devices.
+ * Current default is 8. This can be increased if needed.
+ * \param[out] num_ep_devices The number of EP devices added to ep_devices.
+ * \return true if the factory can create an execution provider that uses `device`.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(GetSupportedDevices, _In_ OrtEpFactory* this_ptr,
+ _In_reads_(num_devices) const OrtHardwareDevice* const* devices,
+ _In_ size_t num_devices,
+ _Inout_ OrtEpDevice** ep_devices,
+ _In_ size_t max_ep_devices,
+ _Out_ size_t* num_ep_devices);
+
+ /** \brief Function to create an OrtEp instance for use in a Session.
+ *
+ * ORT will call ReleaseEp to release the instance when it is no longer needed.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] devices The OrtHardwareDevice instances that the execution provider was selected to use.
+ * May be a subset of the OrtHardwareDevice instances that the execution provider's factory
+ * set as supported in the call to OrtEpFactory::GetSupportedDevices.
+ * \param[in] ep_metadata_pairs Execution provider metadata that was provided to OrtEpApi::CreateEpDevice, for each
+ * device.
+ * \param[in] num_devices The number of devices the execution provider was selected for.
+ * \param[in] session_options The OrtSessionOptions instance that contains the configuration options for the
+ * session. This will include ep_options from GetSupportedDevices as well as any
+ * user provided overrides.
+ * Execution provider options will have been added with a prefix of 'ep.[ep name].'.
+ * The OrtSessionOptions instance will NOT be valid after this call and should not be
+ * stored for later use.
+ * \param[in] logger The OrtLogger instance for the session that the execution provider should use for logging.
+ * \param[out] ep The OrtEp instance created by the factory.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.22.
+ */
+ ORT_API2_STATUS(CreateEp, _In_ OrtEpFactory* this_ptr,
+ _In_reads_(num_devices) const OrtHardwareDevice* const* devices,
+ _In_reads_(num_devices) const OrtKeyValuePairs* const* ep_metadata_pairs,
+ _In_ size_t num_devices,
+ _In_ const OrtSessionOptions* session_options,
+ _In_ const OrtLogger* logger, _Outptr_ OrtEp** ep);
+
+ /** \brief Release the OrtEp instance.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] ep The OrtEp instance to release.
+ *
+ * \since Version 1.22.
+ */
+ ORT_API_T(void, ReleaseEp, OrtEpFactory* this_ptr, struct OrtEp* ep);
+
+ /** \brief Get the vendor id who owns the execution provider that the factory creates.
+ *
+ * This is typically the PCI vendor ID. See https://pcisig.com/membership/member-companies
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \return vendor_id The vendor ID of the execution provider the factory creates.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(uint32_t, GetVendorId, const OrtEpFactory* this_ptr);
+
+ /** \brief Get the version of the execution provider that the factory creates.
+ *
+ * The version string should adhere to the Semantic Versioning 2.0 specification
+ * (https://github.com/semver/semver/blob/v2.0.0/semver.md).
+ *
+ * The returned string should be a null-terminated, UTF-8 encoded string. ORT will copy it.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \return The execution provider version string.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(const char*, GetVersion, _In_ const OrtEpFactory* this_ptr);
+
+ /** \brief Validate the compatibility of a compiled model with the execution provider factory for one or more devices.
+ *
+ * Given a compatibility info string produced during model compilation, the EP factory should determine whether the
+ * compiled model is compatible with the EP factory when targeting the provided hardware devices. All devices provided
+ * must belong to the same execution provider instance that this factory creates.
+ *
+ * The EP factory implementation should consider the set of devices (e.g., multi-adapter or multi-GPU scenarios) when
+ * evaluating compatibility and set `model_compatibility` accordingly.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] devices Array of OrtHardwareDevice pointers that the EP would run on. All must map to this EP.
+ * \param[in] num_devices Number of entries in `devices`.
+ * \param[in] compatibility_info The compatibility information string produced when the model was compiled.
+ * \param[out] model_compatibility OrtCompiledModelCompatibility value describing the compatibility of the model with the EP.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(ValidateCompiledModelCompatibilityInfo, _In_ OrtEpFactory* this_ptr,
+ _In_reads_(num_devices) const OrtHardwareDevice* const* devices,
+ _In_ size_t num_devices,
+ _In_ const char* compatibility_info,
+ _Out_ OrtCompiledModelCompatibility* model_compatibility);
+
+ /** \brief Create an OrtAllocator that can be shared across sessions for the given OrtMemoryInfo.
+ *
+ * The factory that creates the EP is responsible for providing the allocators required by the EP.
+ * The OrtMemoryInfo instance will match one of the values set in the OrtEpDevice using EpDevice_AddAllocatorInfo.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] memory_info The OrtMemoryInfo to create the allocator for. May be nullptr.
+ * \param[in] allocator_options Optional key-value pairs for allocator options, can be nullptr.
+ * \param[out] allocator The created OrtAllocator instance. Set to nullptr if the default CPU allocator is used.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateAllocator, _In_ OrtEpFactory* this_ptr,
+ _In_ const OrtMemoryInfo* memory_info,
+ _In_opt_ const OrtKeyValuePairs* allocator_options,
+ _Outptr_result_maybenull_ OrtAllocator** allocator);
+
+ /** \brief Release an OrtAllocator created by the factory.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(void, ReleaseAllocator, _In_ OrtEpFactory* this_ptr, _In_ OrtAllocator* allocator);
+
+ /** \brief Create an OrtDataTransferImpl instance for the factory.
+ *
+ * This is used to create an IDataTransfer implementation that can be used to copy data between devices
+ * that the execution provider supports.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[out] data_transfer The created OrtDataTransferImpl instance. Set to nullptr if not required.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateDataTransfer, _In_ OrtEpFactory* this_ptr,
+ _Outptr_result_maybenull_ OrtDataTransferImpl** data_transfer);
+
+ /** \brief Check if execution providers created by the factory are stream aware.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \return True if the factory creates execution providers that are stream aware and it implements CreateSyncStreamForDevice.
+ *
+ * \since Version 1.23.
+ */
+ ORT_API_T(bool, IsStreamAware, _In_ const OrtEpFactory* this_ptr);
+
+ /** \brief Create a synchronization stream for the given memory device.
+ *
+ * This is used to create a synchronization stream for the memory device that can be used for operations outside of
+ * a session.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] memory_device The OrtMemoryDevice to create the synchronization stream for.
+ * \param[in] stream_options Options for stream creation. May be nullptr.
+ * \param[out] stream The created OrtSyncStreamImpl instance. nullptr if the execution provider is not stream aware.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.23.
+ */
+ ORT_API2_STATUS(CreateSyncStreamForDevice, _In_ OrtEpFactory* this_ptr,
+ _In_ const OrtMemoryDevice* memory_device,
+ _In_opt_ const OrtKeyValuePairs* stream_options,
+ _Outptr_ OrtSyncStreamImpl** stream);
+
+ /** \brief Check for known incompatibility reasons between a hardware device and this execution provider.
+ *
+ * This function allows an execution provider to check if a specific hardware device is compatible
+ * with the execution provider. The EP can set specific incompatibility reasons via the
+ * OrtDeviceEpIncompatibilityDetails parameter using OrtEpApi::DeviceEpIncompatibilityDetails_SetDetails.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] hw The hardware device to check for incompatibility.
+ * \param[in,out] details Pre-allocated incompatibility details object created and initialized by ORT.
+ * The EP can use OrtEpApi::DeviceEpIncompatibilityDetails_SetDetails to set
+ * incompatibility information. If the device is compatible, the EP can
+ * leave the object unchanged (it defaults to no incompatibility).
+ *
+ * \note Implementation of this function is optional.
+ * If not implemented, ORT will assume the device is compatible with this EP.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetHardwareDeviceIncompatibilityDetails, _In_ OrtEpFactory* this_ptr,
+ _In_ const OrtHardwareDevice* hw,
+ _Inout_ OrtDeviceEpIncompatibilityDetails* details);
+
+ /** \brief Create an OrtExternalResourceImporterImpl for external resource import.
+ *
+ * This is used to create an external resource importer that enables zero-copy import of
+ * external GPU memory (e.g., D3D12 shared resources) and synchronization primitives
+ * (e.g., D3D12 timeline fences).
+ *
+ * EPs that support external resource import (via CUDA, HIP, Vulkan, or D3D12 APIs) can
+ * implement this to allow applications to share GPU resources without copies.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[in] ep_device The OrtEpDevice to create the external resource importer for.
+ * \param[out] out_importer The created OrtExternalResourceImporterImpl instance.
+ * Set to nullptr if external resource import is not supported.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \note Implementation of this function is optional.
+ * An EP factory should only implement this if it supports external resource import.
+ * If not implemented or not supported, return ORT_NOT_IMPLEMENTED or set out_importer to nullptr.
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(CreateExternalResourceImporterForDevice, _In_ OrtEpFactory* this_ptr,
+ _In_ const OrtEpDevice* ep_device,
+ _Outptr_result_maybenull_ OrtExternalResourceImporterImpl** out_importer);
+
+ /** \brief Returns the number of OrtCustomOpDomains that this factory provides.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[out] num_domains Output parameter set to the number of provided OrtCustomOpDomain instances.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetNumCustomOpDomains, _In_ OrtEpFactory* this_ptr, _Out_ size_t* num_domains);
+
+ /** \brief Gets the EP-specific OrtCustomOpDomains.
+ *
+ * This function is used when running inference on a model that contains EP-specific custom operations.
+ *
+ * Workflow:
+ * 1. The EP factory implements this function to supply a list of OrtCustomOpDomain instances.
+ * 2. The application either 1) calls SessionOptionsAppendExecutionProvider_V2() with an OrtEpDevice containing
+ * the plugin EP's factory or 2) enables auto ep selection.
+ * 3. 1) SessionOptionsAppendExecutionProvider_V2() appends the provided OrtCustomOpDomains to the
+ * session options or 2) ORT registers the OrtCustomOpDomains provided by the EP devices
+ * that could be potentially selected.
+ *
+ * As a result, any session created from these session options will have these custom op domains registered
+ * in ORT, ensuring that the custom ops are properly recognized and validated when the model is loaded.
+ *
+ * Plugin EPs can provide two types of custom ops:
+ * 1. A full OrtCustomOp with a concrete kernel implementation
+ * - A Plugin EP can supply an OrtCustomOp and a corresponding CustomKernel::Compute() implementation.
+ * - In GetCapability(), it calls EpGraphSupportInfo_AddSingleNode() to inform ORT
+ * that the custom node should NOT be fused or compiled. Instead, ORT should invoke
+ * the custom node's Compute() function at runtime.
+ *
+ * 2. A "placeholder" OrtCustomOp with an empty kernel implementation
+ * - A compile-based Plugin EP can supply an OrtCustomOp whose CustomKernel::Compute()
+ * does nothing. The purpose is to satisfy model validation during model loading by
+ * registering the custom op as a valid operator in the session.
+ * - In GetCapability(), the EP should call EpGraphSupportInfo_AddNodesToFuse() to
+ * notify ORT that this custom node should be fused and compiled by the EP.
+ * - In Compile(), the EP executes its compiled bits to perform inference for
+ * the fused custom node.
+ *
+ * Note: The OrtCustomOpDomain instances must be valid while any session is using them.
+ EP factory has the responsibility to release OrtCustomOpDomain instances it creates. It happens
+ * automatically if using the C++ Ort::CustomOpDomain class.
+ *
+ * \param[in] this_ptr The OrtEpFactory instance.
+ * \param[out] domains Array of `num_domains` elements pre-allocated by ORT that should be filled with
+ OrtCustomOpDomain instances created by the EP. The `num_domains` is the value returned by
+ GetNumCustomOpDomains().
+ * \param[in] num_domains The size of the `domains` array pre-allocated by ORT.
+ *
+ * \snippet{doc} snippets.dox OrtStatus Return Value
+ *
+ * \since Version 1.24.
+ */
+ ORT_API2_STATUS(GetCustomOpDomains, _In_ OrtEpFactory* this_ptr,
+ _Out_writes_all_(num_domains) OrtCustomOpDomain** domains, _In_ size_t num_domains);
+};
+
+#ifdef __cplusplus
+}
+#endif
diff --git a/kernel/ocr/paddle.go b/kernel/ocr/paddle.go
new file mode 100644
index 0000000000..67e8ac268e
--- /dev/null
+++ b/kernel/ocr/paddle.go
@@ -0,0 +1,390 @@
+package ocr
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "image"
+ "image/color"
+ "image/draw"
+ _ "image/gif"
+ _ "image/jpeg"
+ _ "image/png"
+ "io"
+ "math"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+
+ "github.com/disintegration/imaging"
+ _ "golang.org/x/image/bmp"
+ _ "golang.org/x/image/tiff"
+ _ "golang.org/x/image/webp"
+ "gopkg.in/yaml.v3"
+)
+
+// PaddleConfig 指定一组检测和识别模型,Linux 使用原生辅助进程以兼容静态内核。
+type PaddleConfig struct {
+ Library string `json:"library"`
+ Worker string `json:"worker"`
+ Directory string `json:"directory"`
+}
+
+type modelConfig struct {
+ Global struct {
+ ModelName string `yaml:"model_name"`
+ } `yaml:"Global"`
+ PostProcess struct {
+ Name string `yaml:"name"`
+ Characters []string `yaml:"character_dict"`
+ Threshold float64 `yaml:"thresh"`
+ BoxThreshold float64 `yaml:"box_thresh"`
+ Unclip float64 `yaml:"unclip_ratio"`
+ } `yaml:"PostProcess"`
+}
+
+type PaddleProvider struct {
+ Config func() PaddleConfig
+ mu sync.Mutex
+ loaded PaddleConfig
+ detector, recognizer *session
+ detection modelConfig
+ characters []string
+}
+
+func (p *PaddleProvider) Available() bool {
+ cfg := p.Config()
+ if cfg.Worker != "" {
+ if _, err := os.Stat(cfg.Worker); err != nil {
+ return false
+ }
+ if _, err := os.Stat(cfg.Library); err != nil {
+ return false
+ }
+ } else if err := initRuntime(cfg.Library); err != nil {
+ return false
+ }
+ for _, path := range []string{"det/inference.onnx", "det/inference.yml", "rec/inference.onnx", "rec/inference.yml"} {
+ if _, err := os.Stat(filepath.Join(cfg.Directory, path)); err != nil {
+ return false
+ }
+ }
+ return true
+}
+
+func readModelConfig(directory, kind string) (modelConfig, error) {
+ var config modelConfig
+ path := filepath.Join(directory, kind, "inference.yml")
+ info, err := os.Stat(path)
+ if err != nil {
+ return config, err
+ }
+ if info.Size() > 1024*1024 {
+ return config, errors.New("OCR model configuration is too large")
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return config, err
+ }
+ err = yaml.Unmarshal(data, &config)
+ if err != nil {
+ return config, err
+ }
+ if !strings.HasPrefix(config.Global.ModelName, "PP-OCRv6_") || !strings.HasSuffix(config.Global.ModelName, "_"+kind) {
+ return config, errors.New("only compatible PP-OCRv6 models are supported")
+ }
+ if kind == "det" && (config.PostProcess.Name != "DBPostProcess" || config.PostProcess.Threshold <= 0 || config.PostProcess.Threshold >= 1 || config.PostProcess.BoxThreshold <= 0 || config.PostProcess.BoxThreshold >= 1 || config.PostProcess.Unclip <= 0 || config.PostProcess.Unclip > 3) {
+ return config, errors.New("unsupported OCR detector configuration")
+ }
+ if kind == "rec" && (config.PostProcess.Name != "CTCLabelDecode" || len(config.PostProcess.Characters) == 0 || len(config.PostProcess.Characters) > 30000) {
+ return config, errors.New("unsupported OCR recognizer configuration")
+ }
+ return config, nil
+}
+
+// ValidateModels 在导入和加载时校验配套配置,不接受自定义算子或外部权重。
+func ValidateModels(directory string) error {
+ det, err := readModelConfig(directory, "det")
+ if err != nil {
+ return err
+ }
+ rec, err := readModelConfig(directory, "rec")
+ if err != nil {
+ return err
+ }
+ if strings.TrimSuffix(det.Global.ModelName, "_det") != strings.TrimSuffix(rec.Global.ModelName, "_rec") {
+ return errors.New("OCR detector and recognizer must use the same model family")
+ }
+ for _, kind := range []string{"det", "rec"} {
+ if _, err := readModelConfig(directory, kind); err != nil {
+ return err
+ }
+ info, err := os.Stat(filepath.Join(directory, kind, "inference.onnx"))
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > 256*1024*1024 {
+ return errors.New("invalid OCR model file")
+ }
+ }
+ return nil
+}
+
+func (p *PaddleProvider) load(cfg PaddleConfig) error {
+ if cfg == p.loaded && p.detector != nil && p.recognizer != nil {
+ return nil
+ }
+ p.close()
+ if err := ValidateModels(cfg.Directory); err != nil {
+ return err
+ }
+ det, err := readModelConfig(cfg.Directory, "det")
+ if err != nil {
+ return err
+ }
+ rec, err := readModelConfig(cfg.Directory, "rec")
+ if err != nil {
+ return err
+ }
+ if err = initRuntime(cfg.Library); err != nil {
+ return err
+ }
+ p.detector, err = newSession(filepath.Join(cfg.Directory, "det", "inference.onnx"))
+ if err != nil {
+ return err
+ }
+ p.recognizer, err = newSession(filepath.Join(cfg.Directory, "rec", "inference.onnx"))
+ if err != nil {
+ p.close()
+ return err
+ }
+ p.detection = det
+ p.characters = append(append([]string{""}, rec.PostProcess.Characters...), " ")
+ p.loaded = cfg
+ return nil
+}
+
+func (p *PaddleProvider) close() {
+ if p.detector != nil {
+ p.detector.close()
+ p.detector = nil
+ }
+ if p.recognizer != nil {
+ p.recognizer.close()
+ p.recognizer = nil
+ }
+}
+
+// Close 释放模型会话,正在进行的识别完成后才会执行。
+func (p *PaddleProvider) Close() { p.mu.Lock(); defer p.mu.Unlock(); p.close() }
+
+type WorkerRequest struct {
+ Config PaddleConfig `json:"config"`
+ Image string `json:"image"`
+}
+
+// Validate 加载两个原生会话,导入时拒绝无法执行的 ONNX 文件。
+func (p *PaddleProvider) Validate(ctx context.Context) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ cfg := p.Config()
+ if cfg.Worker != "" {
+ _, err := runWorker(ctx, cfg, "")
+ return err
+ }
+ if err := p.load(cfg); err != nil {
+ return err
+ }
+ detected, err := p.detector.run(ctx, make([]float32, 3*32*32), []int64{1, 3, 32, 32})
+ if err != nil {
+ return err
+ }
+ if _, err = detectBoxes(detected, 32, 32, p.detection); err != nil {
+ return err
+ }
+ recognized, err := p.recognizer.run(ctx, make([]float32, 3*48*320), []int64{1, 3, 48, 320})
+ if err != nil {
+ return err
+ }
+ _, _, err = decodeCTC(recognized, p.characters)
+ return err
+}
+
+func runWorker(ctx context.Context, cfg PaddleConfig, path string) ([]map[string]string, error) {
+ worker := cfg.Worker
+ cfg.Worker = ""
+ request, err := json.Marshal(WorkerRequest{cfg, path})
+ if err != nil {
+ return nil, err
+ }
+ command := exec.CommandContext(ctx, worker)
+ command.Stdin = bytes.NewReader(request)
+ var stderr bytes.Buffer
+ command.Stderr = &stderr
+ output, err := command.Output()
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ if err != nil {
+ return nil, fmt.Errorf("native OCR worker: %w: %s", err, stderr.String())
+ }
+ var rows []map[string]string
+ if err = json.Unmarshal(output, &rows); err != nil {
+ return nil, err
+ }
+ return rows, nil
+}
+
+func (p *PaddleProvider) Recognize(ctx context.Context, path string) ([]map[string]string, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ cfg := p.Config()
+ if cfg.Worker != "" {
+ return runWorker(ctx, cfg, path)
+ }
+ if err := p.load(cfg); err != nil {
+ return nil, err
+ }
+ input, err := decodeImage(path)
+ if err != nil {
+ return nil, err
+ }
+ background := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dx(), input.Bounds().Dy()))
+ draw.Draw(background, background.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
+ draw.Draw(background, background.Bounds(), input, input.Bounds().Min, draw.Over)
+ input = imaging.Clone(background)
+ bounds := input.Bounds()
+ w, h := bounds.Dx(), bounds.Dy()
+ scale := math.Min(1, 960/float64(max(w, h)))
+ dw, dh := max(32, int(math.Round(float64(w)*scale/32))*32), max(32, int(math.Round(float64(h)*scale/32))*32)
+ detected, err := p.detector.run(ctx, imageTensor(input, dw, dh, true), []int64{1, 3, int64(dh), int64(dw)})
+ if err != nil {
+ return nil, err
+ }
+ boxes, err := detectBoxes(detected, w, h, p.detection)
+ if err != nil {
+ return nil, err
+ }
+ rows := make([]map[string]string, 0, len(boxes))
+ for _, box := range boxes {
+ if err = ctx.Err(); err != nil {
+ return nil, err
+ }
+ crop := cropBox(input, box)
+ rw := max(320, min(3200, int(math.Ceil(float64(crop.Bounds().Dx())*48/float64(crop.Bounds().Dy())))))
+ inputData := recognitionTensor(crop, rw)
+ result, runErr := p.recognizer.run(ctx, inputData, []int64{1, 3, 48, int64(rw)})
+ if runErr != nil {
+ return nil, runErr
+ }
+ text, confidence, decodeErr := decodeCTC(result, p.characters)
+ if decodeErr != nil {
+ return nil, decodeErr
+ }
+ if strings.TrimSpace(text) == "" || confidence < 0.5 {
+ continue
+ }
+ left, top, right, bottom := box.bounds()
+ rows = append(rows, map[string]string{"level": "5", "page_num": "1", "block_num": "1", "par_num": "1", "line_num": strconv.Itoa(len(rows) + 1), "word_num": "1", "left": strconv.Itoa(int(math.Max(0, left))), "top": strconv.Itoa(int(math.Max(0, top))), "width": strconv.Itoa(int(math.Min(float64(w), right) - math.Max(0, left))), "height": strconv.Itoa(int(math.Min(float64(h), bottom) - math.Max(0, top))), "conf": strconv.FormatFloat(confidence*100, 'f', 2, 64), "text": text})
+ }
+ return rows, nil
+}
+
+func decodeImage(path string) (image.Image, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ info, err := file.Stat()
+ if err != nil {
+ return nil, err
+ }
+ if info.Size() > 32*1024*1024 {
+ return nil, errors.New("OCR image exceeds 32 MiB")
+ }
+ cfg, _, err := image.DecodeConfig(file)
+ if err != nil {
+ return nil, err
+ }
+ if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > 24000000 {
+ return nil, errors.New("OCR image exceeds 24 million pixels")
+ }
+ if _, err = file.Seek(0, io.SeekStart); err != nil {
+ return nil, err
+ }
+ img, _, err := image.Decode(file)
+ return img, err
+}
+
+func imageTensor(img image.Image, w, h int, detector bool) []float32 {
+ resized := imaging.Resize(img, w, h, imaging.Linear)
+ data := make([]float32, 3*w*h)
+ mean, std := [3]float32{.485, .456, .406}, [3]float32{.229, .224, .225}
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ pixel := resized.NRGBAAt(x, y)
+ channels := [3]uint8{pixel.B, pixel.G, pixel.R}
+ for c, value := range channels {
+ v := float32(value) / 255
+ if detector {
+ v = (v - mean[c]) / std[c]
+ } else {
+ v = (v - .5) / .5
+ }
+ data[c*w*h+y*w+x] = v
+ }
+ }
+ }
+ return data
+}
+
+func recognitionTensor(img image.Image, width int) []float32 {
+ w := min(width, max(1, int(math.Ceil(float64(img.Bounds().Dx())*48/float64(img.Bounds().Dy())))))
+ resized := imageTensor(img, w, 48, false)
+ result := make([]float32, 3*48*width)
+ for c := 0; c < 3; c++ {
+ for y := 0; y < 48; y++ {
+ copy(result[c*48*width+y*width:c*48*width+y*width+w], resized[c*48*w+y*w:c*48*w+(y+1)*w])
+ }
+ }
+ return result
+}
+
+func decodeCTC(result tensor, characters []string) (string, float64, error) {
+ if len(result.shape) != 3 || result.shape[0] != 1 || result.shape[2] != int64(len(characters)) || result.shape[1] <= 0 || result.shape[1]*result.shape[2] != int64(len(result.data)) {
+ return "", 0, errors.New("OCR output does not match character dictionary")
+ }
+ var text strings.Builder
+ last, count, confidence := -1, 0, float64(0)
+ classes := len(characters)
+ for offset := 0; offset < len(result.data); offset += classes {
+ best := 0
+ for index := 1; index < classes; index++ {
+ if result.data[offset+index] > result.data[offset+best] {
+ best = index
+ }
+ }
+ if best != 0 && best != last {
+ text.WriteString(characters[best])
+ confidence += float64(result.data[offset+best])
+ count++
+ }
+ last = best
+ }
+ if count == 0 {
+ return "", 0, nil
+ }
+ return text.String(), confidence / float64(count), nil
+}
diff --git a/kernel/ocr/paddle_test.go b/kernel/ocr/paddle_test.go
new file mode 100644
index 0000000000..6a9326a46a
--- /dev/null
+++ b/kernel/ocr/paddle_test.go
@@ -0,0 +1,96 @@
+package ocr
+
+import (
+ "context"
+ "image"
+ "image/color"
+ "image/draw"
+ "image/png"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/image/font"
+ "golang.org/x/image/font/gofont/goregular"
+ "golang.org/x/image/font/opentype"
+ "golang.org/x/image/math/fixed"
+)
+
+func TestCTCBlankAndRepeatedCharacters(t *testing.T) {
+ data := []float32{0, .9, 0, 0, .8, 0, .9, 0, 0, 0, .7, 0, 0, 0, .8}
+ text, confidence, err := decodeCTC(tensor{data, []int64{1, 5, 3}}, []string{"", "字", " "})
+ if err != nil || text != "字字 " || confidence < .79 || confidence > .81 {
+ t.Fatalf("text=%q confidence=%f err=%v", text, confidence, err)
+ }
+ if _, _, err = decodeCTC(tensor{data, []int64{1, 5, 3}}, []string{"", "字"}); err == nil {
+ t.Fatal("mismatched dictionary was accepted")
+ }
+}
+
+func TestDetectorRejectsUnexpectedShape(t *testing.T) {
+ if _, err := detectBoxes(tensor{make([]float32, 16), []int64{1, 2, 2, 4}}, 40, 40, modelConfig{}); err == nil {
+ t.Fatal("unexpected detector channels were accepted")
+ }
+}
+
+// TestNativePaddleOCR 在配置模型、原生库和样例图后执行,整个过程不启动界面或内核服务器。
+func TestNativePaddleOCR(t *testing.T) {
+ assets, library, fixture := os.Getenv("SIYUAN_OCR_TEST_ASSETS"), os.Getenv("SIYUAN_OCR_TEST_LIBRARY"), os.Getenv("SIYUAN_OCR_TEST_IMAGE")
+ if assets == "" || library == "" {
+ t.Skip("native OCR resources are not configured")
+ }
+ expected := os.Getenv("SIYUAN_OCR_TEST_EXPECT")
+ if fixture == "" {
+ fixture = filepath.Join(t.TempDir(), "ocr.png")
+ typeface, err := opentype.Parse(goregular.TTF)
+ if err != nil {
+ t.Fatal(err)
+ }
+ face, err := opentype.NewFace(typeface, &opentype.FaceOptions{Size: 40, DPI: 72, Hinting: font.HintingFull})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer face.Close()
+ img := image.NewRGBA(image.Rect(0, 0, 500, 100))
+ draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
+ drawer := font.Drawer{Dst: img, Src: image.NewUniform(color.Black), Face: face, Dot: fixed.P(20, 65)}
+ drawer.DrawString("SiYuan OCR 123")
+ file, err := os.Create(fixture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = png.Encode(file, img); err != nil {
+ file.Close()
+ t.Fatal(err)
+ }
+ if err = file.Close(); err != nil {
+ t.Fatal(err)
+ }
+ expected = "SiYuan OCR 123"
+ }
+ for _, size := range []string{"tiny", "small"} {
+ t.Run(size, func(t *testing.T) {
+ provider := &PaddleProvider{Config: func() PaddleConfig { return PaddleConfig{Library: library, Directory: filepath.Join(assets, size)} }}
+ defer provider.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ rows, err := provider.Recognize(ctx, fixture)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var text strings.Builder
+ for _, row := range rows {
+ text.WriteString(row["text"])
+ t.Log(row["text"])
+ }
+ if text.Len() == 0 {
+ t.Fatal("native OCR returned no text")
+ }
+ if expected != "" && !strings.Contains(text.String(), expected) {
+ t.Fatalf("missing expected text %q in %q", expected, text.String())
+ }
+ })
+ }
+}
diff --git a/kernel/ocr/provider.go b/kernel/ocr/provider.go
new file mode 100644
index 0000000000..ed592c3ee7
--- /dev/null
+++ b/kernel/ocr/provider.go
@@ -0,0 +1,90 @@
+package ocr
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+)
+
+type ProviderID string
+
+const (
+ Tesseract ProviderID = "tesseract"
+ PaddleOCR ProviderID = "paddleocr"
+)
+
+var (
+ ErrUnknownProvider = errors.New("unknown OCR provider")
+ ErrUnavailable = errors.New("OCR provider is unavailable")
+)
+
+// Provider 只负责识别,结果存储和搜索索引由调用方统一维护。
+// 结果保留字符串列,兼容现有 OCR HTTP 接口的 ocrJSON 字段。
+type Provider interface {
+ Available() bool
+ Recognize(context.Context, string) ([]map[string]string, error)
+}
+
+// Registry 串行调度识别,避免多个调用同时占用模型内存。
+type Registry struct {
+ mu sync.RWMutex
+ providers map[ProviderID]Provider
+ slot chan struct{}
+}
+
+func NewRegistry() *Registry {
+ return &Registry{
+ providers: map[ProviderID]Provider{},
+ slot: make(chan struct{}, 1),
+ }
+}
+
+func (r *Registry) Register(id ProviderID, provider Provider) error {
+ if id == "" || provider == nil {
+ return errors.New("OCR provider ID and implementation are required")
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if _, exists := r.providers[id]; exists {
+ return fmt.Errorf("OCR provider %q is already registered", id)
+ }
+ r.providers[id] = provider
+ return nil
+}
+
+func (r *Registry) Available(id ProviderID) bool {
+ r.mu.RLock()
+ provider := r.providers[id]
+ r.mu.RUnlock()
+ return provider != nil && provider.Available()
+}
+
+func (r *Registry) Recognize(ctx context.Context, id ProviderID, imagePath string) ([]map[string]string, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ r.mu.RLock()
+ provider := r.providers[id]
+ r.mu.RUnlock()
+ if provider == nil {
+ return nil, fmt.Errorf("%w: %s", ErrUnknownProvider, id)
+ }
+ if !provider.Available() {
+ return nil, fmt.Errorf("%w: %s", ErrUnavailable, id)
+ }
+
+ select {
+ case r.slot <- struct{}{}:
+ defer func() { <-r.slot }()
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if !provider.Available() {
+ return nil, fmt.Errorf("%w: %s", ErrUnavailable, id)
+ }
+ return provider.Recognize(ctx, imagePath)
+}
diff --git a/kernel/ocr/provider_test.go b/kernel/ocr/provider_test.go
new file mode 100644
index 0000000000..40568b04af
--- /dev/null
+++ b/kernel/ocr/provider_test.go
@@ -0,0 +1,123 @@
+package ocr
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+ "time"
+)
+
+type testProvider struct {
+ available bool
+ recognize func(context.Context, string) ([]map[string]string, error)
+}
+
+func (p *testProvider) Available() bool { return p.available }
+
+func (p *testProvider) Recognize(ctx context.Context, path string) ([]map[string]string, error) {
+ return p.recognize(ctx, path)
+}
+
+func TestProviderSelection(t *testing.T) {
+ r := NewRegistry()
+ for _, id := range []ProviderID{Tesseract, PaddleOCR} {
+ id := id
+ if err := r.Register(id, &testProvider{
+ available: true,
+ recognize: func(_ context.Context, path string) ([]map[string]string, error) {
+ return []map[string]string{{"text": string(id), "path": path, "conf": "99"}}, nil
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, id := range []ProviderID{Tesseract, PaddleOCR} {
+ rows, err := r.Recognize(context.Background(), id, "image.png")
+ want := []map[string]string{{"text": string(id), "path": "image.png", "conf": "99"}}
+ if err != nil || !reflect.DeepEqual(rows, want) {
+ t.Fatalf("provider %s: rows=%v, err=%v", id, rows, err)
+ }
+ }
+ if err := r.Register(Tesseract, &testProvider{}); err == nil {
+ t.Fatal("duplicate registration succeeded")
+ }
+}
+
+func TestProviderUnavailableDoesNotFallBack(t *testing.T) {
+ r := NewRegistry()
+ called := false
+ if err := r.Register(Tesseract, &testProvider{
+ available: true,
+ recognize: func(context.Context, string) ([]map[string]string, error) {
+ called = true
+ return nil, nil
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Register(PaddleOCR, &testProvider{}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.Recognize(context.Background(), PaddleOCR, "image.png"); !errors.Is(err, ErrUnavailable) {
+ t.Fatalf("unavailable provider: %v", err)
+ }
+ if _, err := r.Recognize(context.Background(), "missing", "image.png"); !errors.Is(err, ErrUnknownProvider) {
+ t.Fatalf("unknown provider: %v", err)
+ }
+ if called {
+ t.Fatal("another provider was used without selecting it")
+ }
+}
+
+func TestProviderCancellationWhileQueued(t *testing.T) {
+ r := NewRegistry()
+ started, release := make(chan struct{}), make(chan struct{})
+ if err := r.Register(PaddleOCR, &testProvider{
+ available: true,
+ recognize: func(ctx context.Context, path string) ([]map[string]string, error) {
+ if path != "first.png" {
+ t.Error("canceled request reached the provider")
+ return nil, nil
+ }
+ close(started)
+ select {
+ case <-release:
+ return nil, nil
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ done := make(chan error, 1)
+ go func() {
+ _, err := r.Recognize(context.Background(), PaddleOCR, "first.png")
+ done <- err
+ }()
+ <-started
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if _, err := r.Recognize(ctx, PaddleOCR, "second.png"); !errors.Is(err, context.DeadlineExceeded) {
+ t.Errorf("canceled request: %v", err)
+ }
+ close(release)
+ if err := <-done; err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestProviderFailureIsPreserved(t *testing.T) {
+ r := NewRegistry()
+ want := errors.New("model inference failed")
+ if err := r.Register(PaddleOCR, &testProvider{
+ available: true,
+ recognize: func(context.Context, string) ([]map[string]string, error) { return nil, want },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := r.Recognize(context.Background(), PaddleOCR, "image.png"); !errors.Is(err, want) {
+ t.Fatalf("provider error was replaced: %v", err)
+ }
+}
diff --git a/kernel/ocr/runtime.c b/kernel/ocr/runtime.c
new file mode 100644
index 0000000000..e390dcaf2b
--- /dev/null
+++ b/kernel/ocr/runtime.c
@@ -0,0 +1,168 @@
+//go:build cgo
+
+#include "runtime.h"
+#include "onnxruntime_c_api.h"
+#include <stdlib.h>
+#include <string.h>
+#if defined(_WIN32)
+#include <windows.h>
+#else
+#include <dlfcn.h>
+#endif
+#if defined(__APPLE__)
+#include <TargetConditionals.h>
+#if TARGET_OS_IPHONE
+extern const OrtApiBase *ORT_API_CALL OrtGetApiBase(void) __attribute__((weak_import));
+#endif
+#endif
+
+static const OrtApi *sy_api;
+static OrtEnv *sy_env;
+struct SyOCRSession { OrtSession *session; char *input; char *output; };
+struct SyOCROutput { OrtValue *value; float *data; int64_t shape[8]; size_t rank; size_t count; };
+
+static char *sy_message(const char *message) {
+ size_t size = strlen(message) + 1;
+ char *result = malloc(size);
+ if (result) memcpy(result, message, size);
+ return result;
+}
+
+static char *sy_status(OrtStatus *status) {
+ if (!status) return NULL;
+ char *result = sy_message(sy_api->GetErrorMessage(status));
+ sy_api->ReleaseStatus(status);
+ return result;
+}
+
+char *sy_ocr_init(const char *library) {
+ if (sy_env) return NULL;
+ const OrtApiBase *(ORT_API_CALL *get_api)(void) = NULL;
+#if defined(__APPLE__) && TARGET_OS_IPHONE
+ get_api = OrtGetApiBase;
+#elif defined(_WIN32)
+ int size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, library, -1, NULL, 0);
+ wchar_t *path = calloc(size, sizeof(wchar_t));
+ if (!path || !size) { free(path); return sy_message("Invalid ONNX Runtime library path"); }
+ MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, library, -1, path, size);
+ HMODULE handle = LoadLibraryExW(path, NULL, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS);
+ free(path);
+ if (!handle) return sy_message("Cannot load ONNX Runtime library");
+ get_api = (void *)GetProcAddress(handle, "OrtGetApiBase");
+#else
+ void *handle = dlopen(library, RTLD_NOW | RTLD_LOCAL);
+ if (!handle) return sy_message(dlerror());
+ get_api = dlsym(handle, "OrtGetApiBase");
+#endif
+ if (!get_api) return sy_message("ONNX Runtime C API is unavailable");
+ /* 所用接口均在 API 23 中,兼容 Intel macOS 的官方 1.23.2 运行库。 */
+ sy_api = get_api()->GetApi(23);
+ if (!sy_api) return sy_message("ONNX Runtime API version is incompatible");
+ return sy_status(sy_api->CreateEnv(ORT_LOGGING_LEVEL_WARNING, "siyuan-ocr", &sy_env));
+}
+
+char *sy_ocr_session(const void *model, size_t size, SyOCRSession **session) {
+ if (!sy_env) return sy_message("ONNX Runtime is not initialized");
+ SyOCRSession *result = calloc(1, sizeof(SyOCRSession));
+ if (!result) return sy_message("Cannot allocate OCR session");
+ OrtSessionOptions *options = NULL;
+ OrtAllocator *allocator = NULL;
+ OrtTypeInfo *type = NULL;
+ OrtStatus *status = sy_api->CreateSessionOptions(&options);
+ if (!status) status = sy_api->SetIntraOpNumThreads(options, 2);
+ if (!status) status = sy_api->SetSessionGraphOptimizationLevel(options, ORT_ENABLE_ALL);
+ if (!status) status = sy_api->AddSessionConfigEntry(options, "session.intra_op.allow_spinning", "0");
+ if (!status) status = sy_api->CreateSessionFromArray(sy_env, model, size, options, &result->session);
+ if (options) sy_api->ReleaseSessionOptions(options);
+ size_t inputs = 0, outputs = 0;
+ if (!status) status = sy_api->SessionGetInputCount(result->session, &inputs);
+ if (!status) status = sy_api->SessionGetOutputCount(result->session, &outputs);
+ if (!status && (inputs != 1 || outputs != 1)) {
+ sy_ocr_close(result);
+ return sy_message("OCR models must have one input and one output");
+ }
+ const OrtTensorTypeAndShapeInfo *info = NULL;
+ ONNXTensorElementDataType element;
+ size_t rank = 0;
+ int64_t dims[4];
+ if (!status) status = sy_api->SessionGetInputTypeInfo(result->session, 0, &type);
+ if (!status) status = sy_api->CastTypeInfoToTensorInfo(type, &info);
+ if (!status && !info) {
+ sy_api->ReleaseTypeInfo(type);
+ sy_ocr_close(result);
+ return sy_message("OCR model input must be a tensor");
+ }
+ if (!status) status = sy_api->GetTensorElementType(info, &element);
+ if (!status) status = sy_api->GetDimensionsCount(info, &rank);
+ if (!status && rank == 4) status = sy_api->GetDimensions(info, dims, 4);
+ if (type) sy_api->ReleaseTypeInfo(type);
+ if (!status && (element != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT || rank != 4 || dims[1] != 3)) {
+ sy_ocr_close(result);
+ return sy_message("OCR model input must be a float32 NCHW image with three channels");
+ }
+ if (!status) status = sy_api->GetAllocatorWithDefaultOptions(&allocator);
+ if (!status) status = sy_api->SessionGetInputName(result->session, 0, allocator, &result->input);
+ if (!status) status = sy_api->SessionGetOutputName(result->session, 0, allocator, &result->output);
+ if (status) { char *error = sy_status(status); sy_ocr_close(result); return error; }
+ *session = result;
+ return NULL;
+}
+
+void sy_ocr_close(SyOCRSession *session) {
+ if (!session) return;
+ OrtAllocator *allocator = NULL;
+ OrtStatus *status = sy_api->GetAllocatorWithDefaultOptions(&allocator);
+ if (status) sy_api->ReleaseStatus(status);
+ if (allocator) {
+ if (session->input) allocator->Free(allocator, session->input);
+ if (session->output) allocator->Free(allocator, session->output);
+ }
+ if (session->session) sy_api->ReleaseSession(session->session);
+ free(session);
+}
+
+char *sy_ocr_options(void **options) { return sy_status(sy_api->CreateRunOptions((OrtRunOptions **)options)); }
+void sy_ocr_cancel(void *options) {
+ OrtStatus *status = sy_api->RunOptionsSetTerminate(options);
+ if (status) sy_api->ReleaseStatus(status);
+}
+void sy_ocr_free_options(void *options) { sy_api->ReleaseRunOptions(options); }
+
+char *sy_ocr_run(SyOCRSession *session, void *options, float *input, size_t count, const int64_t *shape, SyOCROutput **output) {
+ OrtMemoryInfo *memory = NULL;
+ OrtValue *value = NULL;
+ SyOCROutput *result = calloc(1, sizeof(SyOCROutput));
+ if (!result) return sy_message("Cannot allocate OCR output");
+ OrtStatus *status = sy_api->CreateCpuMemoryInfo(OrtArenaAllocator, OrtMemTypeDefault, &memory);
+ if (!status) status = sy_api->CreateTensorWithDataAsOrtValue(memory, input, count * sizeof(float), shape, 4, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, &value);
+ if (!status) status = sy_api->Run(session->session, options, (const char *const *)&session->input, (const OrtValue *const *)&value, 1, (const char *const *)&session->output, 1, &result->value);
+ if (value) sy_api->ReleaseValue(value);
+ if (memory) sy_api->ReleaseMemoryInfo(memory);
+ OrtTensorTypeAndShapeInfo *info = NULL;
+ ONNXTensorElementDataType element;
+ if (!status) status = sy_api->GetTensorTypeAndShape(result->value, &info);
+ if (!status) status = sy_api->GetTensorElementType(info, &element);
+ if (!status) status = sy_api->GetDimensionsCount(info, &result->rank);
+ if (!status) status = sy_api->GetTensorShapeElementCount(info, &result->count);
+ if (!status && (element != ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT || result->rank > 8 || result->count > 100000000)) {
+ sy_api->ReleaseTensorTypeAndShapeInfo(info);
+ sy_ocr_free_output(result);
+ return sy_message("Unsupported OCR model output tensor");
+ }
+ if (!status) status = sy_api->GetDimensions(info, result->shape, result->rank);
+ if (!status) status = sy_api->GetTensorMutableData(result->value, (void **)&result->data);
+ if (info) sy_api->ReleaseTensorTypeAndShapeInfo(info);
+ if (status) { char *error = sy_status(status); sy_ocr_free_output(result); return error; }
+ *output = result;
+ return NULL;
+}
+
+int sy_ocr_output(SyOCROutput *output, const float **data, const int64_t **shape, size_t *rank, size_t *count) {
+ *data = output->data; *shape = output->shape; *rank = output->rank; *count = output->count;
+ return 0;
+}
+void sy_ocr_free_output(SyOCROutput *output) {
+ if (!output) return;
+ if (output->value) sy_api->ReleaseValue(output->value);
+ free(output);
+}
diff --git a/kernel/ocr/runtime.go b/kernel/ocr/runtime.go
new file mode 100644
index 0000000000..28cf65d38d
--- /dev/null
+++ b/kernel/ocr/runtime.go
@@ -0,0 +1,108 @@
+//go:build cgo
+
+package ocr
+
+/*
+#cgo linux LDFLAGS: -ldl
+#cgo android LDFLAGS: -ldl
+#include <stdlib.h>
+#include "runtime.h"
+*/
+import "C"
+
+import (
+ "context"
+ "errors"
+ "os"
+ "sync"
+ "unsafe"
+)
+
+var runtimeLock sync.Mutex
+
+type session struct{ native *C.SyOCRSession }
+type tensor struct {
+ data []float32
+ shape []int64
+}
+
+func nativeError(message *C.char) error {
+ if message == nil {
+ return nil
+ }
+ defer C.free(unsafe.Pointer(message))
+ return errors.New(C.GoString(message))
+}
+
+func initRuntime(library string) error {
+ runtimeLock.Lock()
+ defer runtimeLock.Unlock()
+ path := C.CString(library)
+ defer C.free(unsafe.Pointer(path))
+ return nativeError(C.sy_ocr_init(path))
+}
+
+func newSession(path string) (*session, error) {
+ model, err := os.ReadFile(path)
+ if err != nil {
+ return nil, err
+ }
+ if len(model) == 0 || len(model) > 256*1024*1024 {
+ return nil, errors.New("invalid OCR model size")
+ }
+ result := &session{}
+ if err = nativeError(C.sy_ocr_session(unsafe.Pointer(&model[0]), C.size_t(len(model)), &result.native)); err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+
+func (s *session) close() { C.sy_ocr_close(s.native); s.native = nil }
+
+func (s *session) run(ctx context.Context, data []float32, shape []int64) (tensor, error) {
+ if err := ctx.Err(); err != nil {
+ return tensor{}, err
+ }
+ count := int64(1)
+ for _, size := range shape {
+ if size <= 0 || size > 100000000/count {
+ return tensor{}, errors.New("invalid OCR input shape")
+ }
+ count *= size
+ }
+ if len(shape) != 4 || count != int64(len(data)) {
+ return tensor{}, errors.New("invalid OCR input tensor")
+ }
+ var options unsafe.Pointer
+ if err := nativeError(C.sy_ocr_options(&options)); err != nil {
+ return tensor{}, err
+ }
+ defer C.sy_ocr_free_options(options)
+ finished, stopped := make(chan struct{}), make(chan struct{})
+ go func() {
+ defer close(stopped)
+ select {
+ case <-ctx.Done():
+ C.sy_ocr_cancel(options)
+ case <-finished:
+ }
+ }()
+ var output *C.SyOCROutput
+ err := nativeError(C.sy_ocr_run(s.native, options, (*C.float)(unsafe.Pointer(&data[0])), C.size_t(len(data)), (*C.int64_t)(unsafe.Pointer(&shape[0])), &output))
+ close(finished)
+ <-stopped
+ if output != nil {
+ defer C.sy_ocr_free_output(output)
+ }
+ if ctx.Err() != nil {
+ return tensor{}, ctx.Err()
+ }
+ if err != nil {
+ return tensor{}, err
+ }
+ var values *C.float
+ var dims *C.int64_t
+ var rank, size C.size_t
+ C.sy_ocr_output(output, &values, &dims, &rank, &size)
+ return tensor{append([]float32(nil), unsafe.Slice((*float32)(unsafe.Pointer(values)), int(size))...), append([]int64(nil), unsafe.Slice((*int64)(unsafe.Pointer(dims)), int(rank))...)}, nil
+}
diff --git a/kernel/ocr/runtime.h b/kernel/ocr/runtime.h
new file mode 100644
index 0000000000..89d166072c
--- /dev/null
+++ b/kernel/ocr/runtime.h
@@ -0,0 +1,15 @@
+#pragma once
+#include <stddef.h>
+#include <stdint.h>
+
+typedef struct SyOCRSession SyOCRSession;
+typedef struct SyOCROutput SyOCROutput;
+char *sy_ocr_init(const char *library);
+char *sy_ocr_session(const void *model, size_t size, SyOCRSession **session);
+void sy_ocr_close(SyOCRSession *session);
+char *sy_ocr_options(void **options);
+void sy_ocr_cancel(void *options);
+void sy_ocr_free_options(void *options);
+char *sy_ocr_run(SyOCRSession *session, void *options, float *input, size_t count, const int64_t *shape, SyOCROutput **output);
+int sy_ocr_output(SyOCROutput *output, const float **data, const int64_t **shape, size_t *rank, size_t *count);
+void sy_ocr_free_output(SyOCROutput *output);
diff --git a/kernel/ocr/runtime_nocgo.go b/kernel/ocr/runtime_nocgo.go
new file mode 100644
index 0000000000..97cae2ac54
--- /dev/null
+++ b/kernel/ocr/runtime_nocgo.go
@@ -0,0 +1,18 @@
+//go:build !cgo
+
+package ocr
+
+import "context"
+
+type session struct{}
+type tensor struct {
+ data []float32
+ shape []int64
+}
+
+func initRuntime(string) error { return ErrUnavailable }
+func newSession(string) (*session, error) { return nil, ErrUnavailable }
+func (*session) close() {}
+func (*session) run(context.Context, []float32, []int64) (tensor, error) {
+ return tensor{}, ErrUnavailable
+}
diff --git a/kernel/sql/block.go b/kernel/sql/block.go
index 631b41d455..2be0cf8d86 100644
--- a/kernel/sql/block.go
+++ b/kernel/sql/block.go
@@ -25,7 +25,6 @@ import (
"github.com/88250/gulu"
"github.com/88250/lute/ast"
- "github.com/88250/lute/editor"
"github.com/88250/lute/html"
"github.com/88250/lute/parse"
"github.com/siyuan-note/logging"
@@ -170,23 +169,24 @@ func indexNode(tx *sql.Tx, id, boxID string) (err error) {
return
}
- content := nodeStaticContent(node, nil, true, indexAssetPath, true, true)
- content = strings.ReplaceAll(content, editor.Zwsp, "")
+ block, _ := buildBlockFromNode(node, tree)
var rowID int64
if rowID, err = blockRowIDByBlockID(tx, id); err != nil {
tx.Rollback()
return
}
- stmt := "UPDATE blocks_fts SET content = ? WHERE rowid = ?"
- if err = execStmtTx(tx, stmt, content, rowID); err != nil {
+ stmt := "UPDATE blocks_fts SET content = ?, fcontent = ? WHERE rowid = ?"
+ if err = execStmtTx(tx, stmt, block.Content, block.FContent, rowID); err != nil {
tx.Rollback()
return
}
- stmt = "UPDATE blocks SET content = ? WHERE id = ?"
- if err = execStmtTx(tx, stmt, content, id); err != nil {
+ stmt = "UPDATE blocks SET content = ?, fcontent = ?, length = ? WHERE id = ?"
+ if err = execStmtTx(tx, stmt, block.Content, block.FContent, block.Length, id); err != nil {
tx.Rollback()
return
}
+ removeBlockCache(id)
+ putBlockCache(block)
return
}
diff --git a/kernel/sql/ocr.go b/kernel/sql/ocr.go
new file mode 100644
index 0000000000..7588a24c8e
--- /dev/null
+++ b/kernel/sql/ocr.go
@@ -0,0 +1,19 @@
+package sql
+
+// QueryOCRAssetDocuments 返回普通笔记本中引用资源的文档,用于刷新包含 OCR 文本的块索引。
+func QueryOCRAssetDocuments(path string) ([]Asset, error) {
+ rows, err := query("SELECT DISTINCT root_id, box FROM assets WHERE path = ? OR instr(path, ?) = 1 OR instr(path, ?) = 1", path, path+"?", path+"#")
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var result []Asset
+ for rows.Next() {
+ var asset Asset
+ if err = rows.Scan(&asset.RootID, &asset.Box); err != nil {
+ return nil, err
+ }
+ result = append(result, asset)
+ }
+ return result, rows.Err()
+}
diff --git a/kernel/util/ocr.go b/kernel/util/ocr.go
index 60d8e72925..82d06a3fd7 100644
--- a/kernel/util/ocr.go
+++ b/kernel/util/ocr.go
@@ -37,6 +37,7 @@ import (
"github.com/88250/lute/html"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/ocr"
)
var (
@@ -50,16 +51,16 @@ var (
assetsTextsChanged = atomic.Bool{}
)
-func CleanNotExistAssetsTexts() {
+func CleanNotExistAssetsTexts(exists func(string) bool) {
assetsTextsLock.Lock()
defer assetsTextsLock.Unlock()
assetsPath := GetDataAssetsAbsPath()
var toRemoves []string
for asset := range assetsTexts {
- assetAbsPath := strings.TrimPrefix(asset, "assets")
+ assetAbsPath := strings.TrimPrefix(OCRAssetKey(asset), "assets")
assetAbsPath = filepath.Join(assetsPath, assetAbsPath)
- if !filelock.IsExist(assetAbsPath) {
+ if !filelock.IsExist(assetAbsPath) && !exists(asset) {
toRemoves = append(toRemoves, asset)
}
}
@@ -85,14 +86,16 @@ func LoadAssetsTexts() {
return
}
- assetsTextsLock.Lock()
- if err = gulu.JSON.UnmarshalJSON(data, &assetsTexts); err != nil {
+ loaded := map[string]string{}
+ if err = gulu.JSON.UnmarshalJSON(data, &loaded); err == nil && loaded == nil {
+ err = errors.New("OCR texts must be an object")
+ }
+ if err != nil {
logging.LogErrorf("unmarshal assets texts failed: %s", err)
- if err = filelock.Remove(assetsTextsPath); err != nil {
- logging.LogErrorf("removed corrupted assets texts failed: %s", err)
- }
return
}
+ assetsTextsLock.Lock()
+ assetsTexts = loaded
assetsTextsLock.Unlock()
debug.FreeOSMemory()
@@ -114,7 +117,7 @@ func SaveAssetsTexts() {
assetsTextsLock.Lock()
// OCR 功能未开启且 ocr-texts.json 不存在时,如果 assetsTexts 为空则不创建文件
- if !TesseractEnabled && !filelock.IsExist(assetsTextsPath) && 0 == len(assetsTexts) {
+ if !filelock.IsExist(assetsTextsPath) && 0 == len(assetsTexts) {
assetsTextsLock.Unlock()
assetsTextsChanged.Store(false)
return
@@ -140,6 +143,7 @@ func SaveAssetsTexts() {
}
func SetAssetText(asset, text string) {
+ asset = OCRAssetKey(asset)
assetsTextsLock.Lock()
oldText, ok := assetsTexts[asset]
assetsTexts[asset] = text
@@ -152,33 +156,20 @@ func SetAssetText(asset, text string) {
func ExistsAssetText(asset string) (ret bool) {
assetsTextsLock.Lock()
_, ret = assetsTexts[asset]
- assetsTextsLock.Unlock()
- return
-}
-
-func OcrAsset(asset string) (ret []map[string]string, err error) {
- if !TesseractEnabled {
- err = errors.New(Langs[Lang][266])
- return
+ if !ret {
+ _, ret = assetsTexts[OCRAssetKey(asset)]
}
-
- assetsPath := GetDataAssetsAbsPath()
- assetAbsPath := strings.TrimPrefix(asset, "assets")
- assetAbsPath = filepath.Join(assetsPath, assetAbsPath)
- ret = Tesseract(assetAbsPath)
- assetsTextsLock.Lock()
- ocrText := GetOcrJsonText(ret)
- assetsTexts[asset] = ocrText
assetsTextsLock.Unlock()
- if "" != ocrText {
- assetsTextsChanged.Store(true)
- }
return
}
func GetAssetText(asset string) (ret string) {
assetsTextsLock.Lock()
- ret = assetsTexts[asset]
+ var found bool
+ ret, found = assetsTexts[OCRAssetKey(asset)]
+ if !found {
+ ret = assetsTexts[asset]
+ }
assetsTextsLock.Unlock()
return
}
@@ -186,10 +177,19 @@ func GetAssetText(asset string) (ret string) {
func RemoveAssetText(asset string) {
assetsTextsLock.Lock()
delete(assetsTexts, asset)
+ delete(assetsTexts, OCRAssetKey(asset))
assetsTextsLock.Unlock()
assetsTextsChanged.Store(true)
}
+// OCRAssetKey 使同一图片的查询参数和片段引用共享识别结果。
+func OCRAssetKey(asset string) string {
+ if index := strings.IndexAny(asset, "?#"); index >= 0 {
+ return asset[:index]
+ }
+ return asset
+}
+
var tesseractExts = []string{
".png",
".jpg",
@@ -218,16 +218,23 @@ func IsTesseractExtractable(p string) bool {
// tesseractOCRLock 用于 Tesseract OCR 加锁串行执行提升稳定性 https://github.com/siyuan-note/siyuan/issues/7265
var tesseractOCRLock = sync.Mutex{}
-func Tesseract(imgAbsPath string) (ret []map[string]string) {
+type TesseractProvider struct{}
+
+func (TesseractProvider) Available() bool {
+ return ContainerStd == Container && TesseractEnabled
+}
+
+func (TesseractProvider) Recognize(parent context.Context, imgAbsPath string) (ret []map[string]string, err error) {
if ContainerStd != Container || !TesseractEnabled {
+ err = ocr.ErrUnavailable
return
}
- defer logging.Recover()
tesseractOCRLock.Lock()
defer tesseractOCRLock.Unlock()
if !IsTesseractExtractable(imgAbsPath) {
+ err = errors.New("unsupported Tesseract image format")
return
}
@@ -237,28 +244,28 @@ func Tesseract(imgAbsPath string) (ret []map[string]string) {
}
if TesseractMaxSize < uint64(info.Size()) {
+ err = errors.New("image exceeds Tesseract size limit")
return
}
- defer logging.Recover()
-
timeout := 7000
timeoutEnv := os.Getenv("SIYUAN_TESSERACT_TIMEOUT")
if "" != timeoutEnv {
- if timeoutParsed, parseErr := strconv.Atoi(timeoutEnv); nil == parseErr {
+ if timeoutParsed, parseErr := strconv.Atoi(timeoutEnv); nil == parseErr && timeoutParsed > 0 {
timeout = timeoutParsed
} else {
logging.LogWarnf("parse tesseract timeout [%s] failed: %s", timeoutEnv, parseErr)
}
}
- ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Millisecond)
+ ctx, cancel := context.WithTimeout(parent, time.Duration(timeout)*time.Millisecond)
defer cancel()
cmd := exec.CommandContext(ctx, TesseractBin, "-c", "debug_file=/dev/null", imgAbsPath, "stdout", "-l", strings.Join(TesseractLangs, "+"), "tsv")
gulu.CmdAttr(cmd)
- output, err := cmd.CombinedOutput()
+ output, err := cmd.Output()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
logging.LogWarnf("tesseract [path=%s, size=%d] timeout [%dms]", imgAbsPath, info.Size(), timeout)
+ err = ctx.Err()
return
}
@@ -273,6 +280,9 @@ func Tesseract(imgAbsPath string) (ret []map[string]string) {
// 按行分割 TSV 数据
tsv = strings.ReplaceAll(tsv, "\r", "")
lines := strings.Split(tsv, "\n")
+ if len(lines) == 0 || !strings.HasPrefix(lines[0], "level\t") {
+ return nil, errors.New("invalid Tesseract TSV response")
+ }
// 解析 TSV 数据 跳过标题行,从第二行开始处理
for _, line := range lines[1:] {
@@ -317,12 +327,20 @@ func GetOcrJsonText(jsonData []map[string]string) (ret string) {
var tesseractInited = atomic.Bool{}
func WaitForTesseractInit() {
- for {
- if tesseractInited.Load() {
- return
+ _ = WaitForTesseractInitContext(context.Background())
+}
+
+func WaitForTesseractInitContext(ctx context.Context) error {
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for !tesseractInited.Load() {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
}
- time.Sleep(time.Second)
}
+ return ctx.Err()
}
func InitTesseract() {
diff --git a/kernel/util/ocr_test.go b/kernel/util/ocr_test.go
new file mode 100644
index 0000000000..d0616957d2
--- /dev/null
+++ b/kernel/util/ocr_test.go
@@ -0,0 +1,59 @@
+package util
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestOCRTextReferenceVariants(t *testing.T) {
+ path := "assets/ocr-reference-test.png"
+ defer RemoveAssetText(path)
+ SetAssetText(path+"?page=1#fragment", "shared OCR")
+ for _, reference := range []string{path, path + "?page=2", path + "#fragment"} {
+ if !ExistsAssetText(reference) || GetAssetText(reference) != "shared OCR" {
+ t.Fatalf("OCR text was not shared with %s", reference)
+ }
+ }
+}
+
+func TestOCRCleanupRetainsNotebookAssets(t *testing.T) {
+ previous := DataDir
+ DataDir = t.TempDir()
+ defer func() { DataDir = previous }()
+ const path = "assets/notebook-image.png"
+ const missing = "assets/deleted-image.png"
+ SetAssetText(path, "notebook text")
+ SetAssetText(missing, "deleted text")
+ defer RemoveAssetText(path)
+ defer RemoveAssetText(missing)
+ CleanNotExistAssetsTexts(func(asset string) bool { return asset == path })
+ if !ExistsAssetText(path) || ExistsAssetText(missing) {
+ t.Fatal("OCR cleanup ignored notebook asset resolution")
+ }
+}
+
+func TestOCRCorruptCachePreservesSourceAndMemory(t *testing.T) {
+ previous := DataDir
+ DataDir = t.TempDir()
+ defer func() { DataDir = previous }()
+ assets := filepath.Join(DataDir, "assets")
+ if err := os.MkdirAll(assets, 0755); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(assets, "ocr-texts.json")
+ corrupt := []byte(`{"assets/file.png":`)
+ if err := os.WriteFile(file, corrupt, 0644); err != nil {
+ t.Fatal(err)
+ }
+ SetAssetText("assets/file.png", "previous result")
+ defer RemoveAssetText("assets/file.png")
+ LoadAssetsTexts()
+ if GetAssetText("assets/file.png") != "previous result" {
+ t.Fatal("invalid cache changed existing text")
+ }
+ data, err := os.ReadFile(file)
+ if err != nil || string(data) != string(corrupt) {
+ t.Fatalf("invalid cache was modified: %s %v", data, err)
+ }
+}
diff --git a/scripts/build-ocr-harmony.py b/scripts/build-ocr-harmony.py
new file mode 100644
index 0000000000..a09637e98c
--- /dev/null
+++ b/scripts/build-ocr-harmony.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+"""使用鸿蒙 NDK 构建固定版本的 ONNX Runtime,不编译或启动思源内核。"""
+
+import argparse
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import tarfile
+import tempfile
+
+REVISION = "3a728b75062256951b6e19ce718907cf1a1d4cf0"
+
+
+def replace_required(path, before, after):
+ content = path.read_text(encoding="utf-8")
+ if before not in content:
+ raise ValueError(f"Unsupported ONNX Runtime source: {path}")
+ path.write_text(content.replace(before, after), encoding="utf-8")
+
+
+def patch_source(source):
+ # FP32 和 INT8 使用 NEON,避开旧版鸿蒙 Clang 不支持的 BF16 快速路径和 FP16 向量指令。
+ guard = "#if defined(__aarch64__) && defined(__linux__)"
+ directories = [source / "onnxruntime/core/mlas", source / "onnxruntime/core/providers/cpu/math", source / "onnxruntime/contrib_ops/cpu"]
+ for directory in directories:
+ for path in directory.rglob("*"):
+ if path.suffix not in (".h", ".cpp", ".cc"):
+ continue
+ content = path.read_text(encoding="utf-8")
+ if guard in content:
+ path.write_text(content.replace(guard, guard + " && !defined(__OHOS__)"), encoding="utf-8")
+ replace_required(source / "onnxruntime/core/mlas/inc/mlas.h", "#if !defined(__APPLE__)", "#if !defined(__APPLE__) && !defined(__OHOS__)")
+ replace_required(source / "cmake/onnxruntime_mlas.cmake", "if (NOT APPLE)\n set(mlas_platform_srcs", "if (NOT APPLE AND NOT SIYUAN_OHOS)\n set(mlas_platform_srcs")
+ replace_required(source / "cmake/CMakeLists.txt", 'if (NOT APPLE AND NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten" AND onnxruntime_target_platform STREQUAL "aarch64")', 'if (NOT APPLE AND NOT SIYUAN_OHOS AND NOT CMAKE_SYSTEM_NAME STREQUAL "Emscripten" AND onnxruntime_target_platform STREQUAL "aarch64")')
+ replace_required(source / "onnxruntime/core/platform/posix/env.cc", "#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(__wasm__) && !defined(_AIX)", "#if !defined(__APPLE__) && !defined(__ANDROID__) && !defined(__wasm__) && !defined(_AIX) && !defined(__OHOS__)")
+ # 动态库使用固定 SONAME,鸿蒙包内不需要版本号软链接。
+ target = source / "cmake/onnxruntime.cmake"
+ content = target.read_text(encoding="utf-8")
+ content = re.sub(r"^[ \t]*(SOVERSION[ \t]+1|VERSION[ \t]+\$\{ORT_VERSION\})[ \t]*$", "", content, flags=re.MULTILINE)
+ target.write_text(content, encoding="utf-8")
+
+
+def export_source(checkout, destination):
+ revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=checkout, text=True).strip()
+ if revision != REVISION:
+ raise ValueError(f"ONNX Runtime source must be {REVISION}, got {revision}")
+ with tempfile.TemporaryFile() as archive:
+ subprocess.run(["git", "archive", REVISION], cwd=checkout, stdout=archive, check=True)
+ archive.seek(0)
+ with tarfile.open(fileobj=archive) as source:
+ for member in source.getmembers():
+ target = (destination / member.name).resolve()
+ if not target.is_relative_to(destination.resolve()) or member.issym() or member.islnk():
+ raise ValueError("Unsafe ONNX Runtime source archive")
+ source.extractall(destination)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source", required=True, type=Path, help="Official ONNX Runtime v1.24.3 checkout")
+ parser.add_argument("--ndk", required=True, type=Path, help="Harmony SDK native directory")
+ parser.add_argument("--protoc", required=True, type=Path, help="Host protoc 3.21.12 executable")
+ parser.add_argument("--output", required=True, type=Path, help="siyuan-harmony/entry/libs directory")
+ parser.add_argument("--arch", choices=("arm64-v8a", "x86_64"), default="arm64-v8a")
+ parser.add_argument("--jobs", type=int, default=2)
+ args = parser.parse_args()
+ if not args.protoc.is_file() or args.jobs < 1:
+ parser.error("A host protoc executable and positive job count are required")
+ ndk = args.ndk.resolve()
+ suffix = ".exe" if (ndk / "llvm/bin/clang.exe").exists() else ""
+ cmake = ndk / ("build-tools/cmake/bin/cmake" + suffix)
+ if not cmake.is_file():
+ parser.error("Harmony NDK CMake executable was not found")
+ ninja = ndk / ("build-tools/cmake/bin/ninja" + suffix)
+ if not ninja.is_file():
+ parser.error("Harmony NDK Ninja executable was not found")
+ # 所有源码适配只作用于临时副本,保留原始上游检出目录。
+ with tempfile.TemporaryDirectory(prefix="siyuan-ocr-harmony-") as working:
+ root = Path(working)
+ source = root / "source"
+ export_source(args.source, source)
+ patch_source(source)
+ toolchain = root / "toolchain.cmake"
+ toolchain.write_text(f'include("{(ndk / "build/cmake/ohos.toolchain.cmake").as_posix()}")\nset(CMAKE_SYSTEM_NAME Linux)\nset(CMAKE_C_FLAGS "${{CMAKE_C_FLAGS}} -D__OHOS__")\nset(CMAKE_CXX_FLAGS "${{CMAKE_CXX_FLAGS}} -D__OHOS__")\n', encoding="utf-8")
+ build = root / "build"
+ subprocess.run([str(cmake), "-S", str(source / "cmake"), "-B", str(build), "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", f"-DCMAKE_TOOLCHAIN_FILE={toolchain}", f"-DOHOS_ARCH={args.arch}", "-DCMAKE_BUILD_TYPE=Release", "-DSIYUAN_OHOS=ON", "-Donnxruntime_CROSS_COMPILING=ON", "-Donnxruntime_BUILD_SHARED_LIB=ON", "-Donnxruntime_BUILD_UNIT_TESTS=OFF", "-Donnxruntime_ENABLE_CPUINFO=OFF", "-Donnxruntime_ENABLE_CPU_FP16_OPS=OFF", "-Donnxruntime_USE_KLEIDIAI=OFF", "-Donnxruntime_USE_SVE=OFF", "-Donnxruntime_RUN_ONNX_TESTS=OFF", "-Donnxruntime_DISABLE_EXTERNAL_INITIALIZERS=ON", f"-DONNX_CUSTOM_PROTOC_EXECUTABLE={args.protoc.resolve()}", "--compile-no-warning-as-error"], check=True)
+ subprocess.run([str(cmake), "--build", str(build), "--target", "onnxruntime", "--parallel", str(args.jobs)], check=True)
+ destination = args.output.resolve() / args.arch
+ destination.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(build / "libonnxruntime.so", destination / "libonnxruntime.so")
+ for name in ("LICENSE", "ThirdPartyNotices.txt"):
+ shutil.copyfile(source / name, destination / ("ONNXRUNTIME-" + name))
+ print(f"Harmony OCR runtime ready: {destination}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/build-release.py b/scripts/build-release.py
index 588b8bd793..3e5c456197 100644
--- a/scripts/build-release.py
+++ b/scripts/build-release.py
@@ -325,6 +325,7 @@ def source_preflight(args, version):
def create_mobile_assets(destination, version):
+ run([sys.executable, ROOT / "scripts/prepare-ocr.py"], ROOT)
destination.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(destination, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
for group in VERIFY.GROUPS:
@@ -340,6 +341,8 @@ def create_mobile_assets(destination, version):
if path.is_symlink() or not path.is_file() or any(
part in {".git", ".idea", ".gitignore", ".DS_Store"} for part in relative.parts):
continue
+ if relative.parts[:3] == ("stage", "ocr", "runtime"):
+ continue
archive.write(path, relative.as_posix())
for filename in ("LICENSE", "THIRD_PARTY_NOTICES.md"):
archive.write(ROOT / filename, filename)
diff --git a/scripts/ocr-assets.json b/scripts/ocr-assets.json
new file mode 100644
index 0000000000..d3ef134099
--- /dev/null
+++ b/scripts/ocr-assets.json
@@ -0,0 +1,90 @@
+{
+ "models": [
+ {
+ "path": "tiny/det/inference.onnx",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.onnx",
+ "sha256": "193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8",
+ "size": 1780590
+ },
+ {
+ "path": "tiny/det/inference.yml",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.yml",
+ "sha256": "3ac018be6f97499a08faa3bbdeb33640968d9307f6736d152902747a9f259593",
+ "size": 883
+ },
+ {
+ "path": "tiny/rec/inference.onnx",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx/resolve/2612ab37152ae0a677521bae4e1e3d4fb4cf7c30/inference.onnx",
+ "sha256": "9ef676d6ed3c88256a2d92c640c44f25b0c40947e111b14b8be8f594091563e6",
+ "size": 4462639
+ },
+ {
+ "path": "tiny/rec/inference.yml",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_rec_onnx/resolve/2612ab37152ae0a677521bae4e1e3d4fb4cf7c30/inference.yml",
+ "sha256": "66170210bad538e83fff3c4a3867e547d6bf20b50d64b20347c4b913f3034ea1",
+ "size": 55571
+ },
+ {
+ "path": "small/det/inference.onnx",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_small_det_onnx/resolve/28fe5895c24fd108c19eb3e8479f4ab385fbfc62/inference.onnx",
+ "sha256": "d73e0058b7a8086bbd57f3d10b8bcd4ff95363f67e06e2762b5e814fe9c9410e",
+ "size": 9880512
+ },
+ {
+ "path": "small/det/inference.yml",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_small_det_onnx/resolve/28fe5895c24fd108c19eb3e8479f4ab385fbfc62/inference.yml",
+ "sha256": "193f435274bf9f0b5f71a929bbfbcf148282df7e633b34e7c373e8f44741b516",
+ "size": 885
+ },
+ {
+ "path": "small/rec/inference.onnx",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_small_rec_onnx/resolve/b8f84f0b80c529de40b4fbb3544b84fa7233a513/inference.onnx",
+ "sha256": "5435fd747c9e0efe15a96d0b378d5bd157e9492ed8fd80edf08f30d02fa24634",
+ "size": 21159378
+ },
+ {
+ "path": "small/rec/inference.yml",
+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv6_small_rec_onnx/resolve/b8f84f0b80c529de40b4fbb3544b84fa7233a513/inference.yml",
+ "sha256": "ab078671bb49f06228eadccd34f1bb501e157f7a047095ffb943ba81512c77d1",
+ "size": 150579
+ }
+ ],
+ "runtime": {
+ "windows-amd64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.24.3/onnxruntime-win-x64-1.24.3.zip",
+ "sha256": "4fbfb85d0e9de9bb6fb8a9866a7cb477cbad404d889b236931bf3f5d547e5f48",
+ "library": "onnxruntime.dll",
+ "size": 74397435
+ },
+ "windows-arm64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.24.3/onnxruntime-win-arm64-1.24.3.zip",
+ "sha256": "0b9ee92bcd1f82f684b574cb413f27595e0d2f7b96ec6d02b30301f45ad313b0",
+ "library": "onnxruntime.dll",
+ "size": 75093351
+ },
+ "linux-amd64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.24.3/onnxruntime-linux-x64-1.24.3.tgz",
+ "sha256": "4c436a280d650f8bf32c921a2bf4de7c42cc32884c51c90e47de991708bbb5a4",
+ "library": "libonnxruntime.so",
+ "size": 8150413
+ },
+ "linux-arm64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.24.3/onnxruntime-linux-aarch64-1.24.3.tgz",
+ "sha256": "15100fb88b4c692cdd6bf2cca5f4a26a3806cebca8136de6681e2aba4b2ea033",
+ "library": "libonnxruntime.so",
+ "size": 7166580
+ },
+ "darwin-arm64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.24.3/onnxruntime-osx-arm64-1.24.3.tgz",
+ "sha256": "c255663d40755f84b1b86373bdb9870bb65f3a2c3d779b3d7ae31aaa00cebb4f",
+ "library": "libonnxruntime.dylib",
+ "size": 30381891
+ },
+ "darwin-amd64": {
+ "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.23.2/onnxruntime-osx-x86_64-1.23.2.tgz",
+ "sha256": "d10359e16347b57d9959f7e80a225a5b4a66ed7d7e007274a15cae86836485a6",
+ "library": "libonnxruntime.dylib",
+ "size": 11676322
+ }
+ }
+}
diff --git a/scripts/prepare-ocr.py b/scripts/prepare-ocr.py
new file mode 100644
index 0000000000..6f9269a2dc
--- /dev/null
+++ b/scripts/prepare-ocr.py
@@ -0,0 +1,145 @@
+#!/usr/bin/env python3
+"""下载并校验随应用分发的 OCR 模型和原生运行时;不在用户运行时下载。"""
+
+import argparse
+import concurrent.futures
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import tarfile
+import tempfile
+import time
+import urllib.request
+import zipfile
+
+ROOT = Path(__file__).resolve().parents[1]
+MANIFEST = json.loads(Path(__file__).with_name("ocr-assets.json").read_text(encoding="utf-8"))
+STAGE = ROOT / "app/stage/ocr"
+
+
+def digest(path, algorithm="sha256"):
+ value = hashlib.new(algorithm)
+ with path.open("rb") as stream:
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+ value.update(chunk)
+ return value.hexdigest()
+
+
+def download(entry, destination):
+ algorithm = "sha256" if "sha256" in entry else "sha512"
+ if destination.is_file() and digest(destination, algorithm) == entry[algorithm]:
+ return
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ for attempt in range(4):
+ handle, name = tempfile.mkstemp(prefix=destination.name + "-", suffix=".tmp", dir=destination.parent)
+ os.close(handle)
+ temporary = Path(name)
+ try:
+ ranged = False
+ if entry.get("size", 0) > 4 * 1024 * 1024:
+ try:
+ download_ranges(entry, temporary)
+ ranged = True
+ except RangeUnsupported:
+ pass
+ if not ranged:
+ with urllib.request.urlopen(entry["url"], timeout=60) as source, temporary.open("wb") as target:
+ shutil.copyfileobj(source, target)
+ if digest(temporary, algorithm) != entry[algorithm]:
+ raise ValueError(f"Checksum mismatch: {entry['url']}")
+ if "size" in entry and temporary.stat().st_size != entry["size"]:
+ raise ValueError(f"Size mismatch: {entry['url']}")
+ os.replace(temporary, destination)
+ return
+ except Exception:
+ temporary.unlink(missing_ok=True)
+ if attempt == 3:
+ raise
+ time.sleep(1)
+
+
+class RangeUnsupported(Exception):
+ pass
+
+
+def download_ranges(entry, destination):
+ size = entry["size"]
+ chunk_size = 2 * 1024 * 1024
+ with destination.open("wb") as stream:
+ stream.truncate(size)
+
+ def part(start):
+ end = min(size, start + chunk_size) - 1
+ request = urllib.request.Request(entry["url"], headers={"Range": f"bytes={start}-{end}"})
+ with urllib.request.urlopen(request, timeout=60) as source:
+ if source.status != 206 or source.headers.get("Content-Range") != f"bytes {start}-{end}/{size}":
+ raise RangeUnsupported()
+ data = source.read(end - start + 2)
+ if len(data) != end - start + 1:
+ raise ValueError("Truncated OCR resource range")
+ with destination.open("r+b") as stream:
+ stream.seek(start)
+ stream.write(data)
+
+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
+ futures = [pool.submit(part, start) for start in range(0, size, chunk_size)]
+ for future in futures:
+ future.result()
+
+
+def prepare_runtime(target, build_worker):
+ entry = MANIFEST["runtime"][target]
+ cache = Path(tempfile.gettempdir()) / "siyuan-ocr-assets" / entry["url"].rsplit("/", 1)[1]
+ download(entry, cache)
+ directory = STAGE / "runtime" / target
+ directory.mkdir(parents=True, exist_ok=True)
+ library = entry["library"]
+ # 仅复制固定名称的库和许可证,归档路径不参与目标路径拼接。
+ if zipfile.is_zipfile(cache):
+ with zipfile.ZipFile(cache) as archive:
+ files = archive.namelist()
+ selected = next(name for name in files if name.endswith("/lib/" + library))
+ (directory / library).write_bytes(archive.read(selected))
+ for name in files:
+ if name.rsplit("/", 1)[-1] in ("LICENSE", "ThirdPartyNotices.txt", "onnxruntime_providers_shared.dll"):
+ (directory / name.rsplit("/", 1)[-1]).write_bytes(archive.read(name))
+ else:
+ with tarfile.open(cache, "r:gz") as archive:
+ files = [member for member in archive.getmembers() if member.isfile()]
+ if "member" in entry:
+ selected = next(member for member in files if member.name == entry["member"])
+ else:
+ selected = next(member for member in files if "/lib/" in member.name and member.name.rsplit("/", 1)[-1].startswith(library.split(".dylib")[0]) and ".a" not in member.name)
+ with archive.extractfile(selected) as source, (directory / library).open("wb") as destination:
+ shutil.copyfileobj(source, destination)
+ for member in files:
+ if member.name.rsplit("/", 1)[-1] in ("LICENSE", "ThirdPartyNotices.txt"):
+ with archive.extractfile(member) as source, (directory / member.name.rsplit("/", 1)[-1]).open("wb") as destination:
+ shutil.copyfileobj(source, destination)
+ if target.startswith("linux-") and build_worker:
+ architecture = target.split("-", 1)[1]
+ environment = os.environ.copy()
+ environment.update(GOOS="linux", GOARCH=architecture, CGO_ENABLED="1")
+ environment["CC"] = "aarch64-linux-gnu-gcc" if architecture == "arm64" and os.uname().machine != "aarch64" else "gcc"
+ subprocess.run(["go", "build", "-trimpath", "-ldflags=-s -w", "-o", str(directory / "siyuan-ocr"), "./ocr/cmd/ocr-worker"], cwd=ROOT / "kernel", env=environment, check=True)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--runtime", choices=["none", *MANIFEST.get("runtime", {})], default="none")
+ parser.add_argument("--build-worker", action="store_true")
+ args = parser.parse_args()
+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
+ futures = [pool.submit(download, entry, STAGE / "models" / entry["path"]) for entry in MANIFEST["models"]]
+ for future in futures:
+ future.result()
+ if args.runtime != "none":
+ prepare_runtime(args.runtime, args.build_worker)
+ print(f"OCR resources ready: {args.runtime}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_prepare_ocr.py b/scripts/test_prepare_ocr.py
new file mode 100644
index 0000000000..69827f2001
--- /dev/null
+++ b/scripts/test_prepare_ocr.py
@@ -0,0 +1,72 @@
+"""OCR 发布资源校验与解包测试,不下载模型或编译内核。"""
+
+import hashlib
+import importlib.util
+import io
+from pathlib import Path
+import tarfile
+import tempfile
+import unittest
+from unittest.mock import patch
+import zipfile
+
+SPEC = importlib.util.spec_from_file_location("prepare_ocr", Path(__file__).with_name("prepare-ocr.py"))
+prepare = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(prepare)
+
+
+class ResourceTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+
+ def entry(self, file):
+ return {"url": file.as_uri(), "sha256": hashlib.sha256(file.read_bytes()).hexdigest(), "size": file.stat().st_size}
+
+ def test_checksum_failure_preserves_previous_resource(self):
+ source = self.root / "source"
+ source.write_bytes(b"invalid replacement")
+ destination = self.root / "model"
+ destination.write_bytes(b"previous model")
+ entry = self.entry(source)
+ entry["sha256"] = "0" * 64
+ with patch.object(prepare.time, "sleep"):
+ with self.assertRaisesRegex(ValueError, "Checksum mismatch"):
+ prepare.download(entry, destination)
+ self.assertEqual(destination.read_bytes(), b"previous model")
+ self.assertEqual(list(self.root.glob("*.tmp")), [])
+
+ def test_windows_runtime_copies_only_libraries_and_licenses(self):
+ archive = self.root / "runtime.zip"
+ with zipfile.ZipFile(archive, "w") as output:
+ for name, content in {"ort/lib/onnxruntime.dll": b"native", "ort/lib/onnxruntime_providers_shared.dll": b"provider", "ort/LICENSE": b"license", "../outside": b"unsafe"}.items():
+ output.writestr(name, content)
+ self.extract(archive, "windows-amd64", "onnxruntime.dll")
+ destination = self.root / "stage/runtime/windows-amd64"
+ self.assertEqual((destination / "onnxruntime.dll").read_bytes(), b"native")
+ self.assertEqual((destination / "onnxruntime_providers_shared.dll").read_bytes(), b"provider")
+ self.assertFalse((self.root / "outside").exists())
+
+ def test_linux_runtime_selects_regular_library_without_symlinks(self):
+ archive = self.root / "runtime.tgz"
+ with tarfile.open(archive, "w:gz") as output:
+ link = tarfile.TarInfo("ort/lib/libonnxruntime.so")
+ link.type, link.linkname = tarfile.SYMTYPE, "libonnxruntime.so.1.24.3"
+ output.addfile(link)
+ content = b"native"
+ library = tarfile.TarInfo("ort/lib/libonnxruntime.so.1.24.3")
+ library.size = len(content)
+ output.addfile(library, io.BytesIO(content))
+ self.extract(archive, "linux-amd64", "libonnxruntime.so")
+ self.assertEqual((self.root / "stage/runtime/linux-amd64/libonnxruntime.so").read_bytes(), b"native")
+
+ def extract(self, archive, target, library):
+ entry = self.entry(archive)
+ entry["library"] = library
+ with patch.object(prepare, "STAGE", self.root / "stage"), patch.object(prepare, "MANIFEST", {"runtime": {target: entry}}), patch.object(prepare.tempfile, "gettempdir", return_value=str(self.root / "cache")):
+ prepare.prepare_runtime(target, False)
+
+
+if __name__ == "__main__":
+ unittest.main()