Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Editor] Avoid to query ML engine several times for the same image #18380

Merged
merged 1 commit into from
Jul 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 40 additions & 31 deletions src/display/editor/stamp.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ class StampEditor extends AnnotationEditor {

#canvas = null;

#hasMLBeenQueried = false;

#observer = null;

#resizeTimeoutId = null;
Expand Down Expand Up @@ -423,6 +425,42 @@ class StampEditor extends AnnotationEditor {
return bitmap;
}

async #mlGuessAltText(bitmap, width, height) {
if (this.#hasMLBeenQueried) {
return;
}
this.#hasMLBeenQueried = true;
if (!this._uiManager.hasMLManager || this.hasAltText()) {
return;
}
const offscreen = new OffscreenCanvas(width, height);
const ctx = offscreen.getContext("2d", { willReadFrequently: true });
ctx.drawImage(
bitmap,
0,
0,
bitmap.width,
bitmap.height,
0,
0,
width,
height
);
const response = await this._uiManager.mlGuess({
service: "image-to-text",
request: {
data: ctx.getImageData(0, 0, width, height).data,
width,
height,
channels: 4,
},
});
const altText = response?.output || "";
if (this.parent && altText && !this.hasAltText()) {
this.altTextData = { altText, decorative: false };
}
}

#drawBitmap(width, height) {
width = Math.ceil(width);
height = Math.ceil(height);
Expand All @@ -436,37 +474,8 @@ class StampEditor extends AnnotationEditor {
? this.#bitmap
: this.#scaleBitmap(width, height);

if (this._uiManager.hasMLManager && !this.hasAltText()) {
const offscreen = new OffscreenCanvas(width, height);
const ctx = offscreen.getContext("2d");
ctx.drawImage(
bitmap,
0,
0,
bitmap.width,
bitmap.height,
0,
0,
width,
height
);
this._uiManager
.mlGuess({
service: "image-to-text",
request: {
data: ctx.getImageData(0, 0, width, height).data,
width,
height,
channels: 4,
},
})
.then(response => {
const altText = response?.output || "";
if (this.parent && altText && !this.hasAltText()) {
this.altTextData = { altText, decorative: false };
}
});
}
this.#mlGuessAltText(bitmap, width, height);

const ctx = canvas.getContext("2d");
ctx.filter = this._uiManager.hcmFilter;
ctx.drawImage(
Expand Down