Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { inject, observer } from "mobx-react";
import React from "react";
import { taskToLSFormat } from "../../../sdk/lsf-utils";
import { cn } from "../../../utils/bem";
import { Spinner } from "../Spinner";
import "./AnnotationPreview.scss";
 
const imgDefaultProps = { crossOrigin: "anonymous" };
 
const wait = (timeout) => new Promise((resolve) => setTimeout(resolve, timeout));
 
class PreviewGenerator {
  static getInstance(labelingConfig) {
    if (PreviewGenerator._instance) return PreviewGenerator._instance;
 
    return (PreviewGenerator._instance = new PreviewGenerator(labelingConfig));
  }
 
  constructor(labelingConfig) {
    this.loaded = false;
    this.running = false;
    this.queue = [];
 
    this.root = document.querySelector(".offscreen");
 
    this.lsf = new window.LabelStudio(this.root, {
      user: { id: 1 },
      interfaces: [],
      config: labelingConfig ?? "",
      onLabelStudioLoad: () => {
        this.loaded = true;
        this.startQueue();
      },
    });
  }
 
  generatePreview(task, annotation) {
    return new Promise((resolve) => {
      this.queue.push({
        task,
        annotation,
        resolve,
      });
 
      this.startQueue();
    });
  }
 
  async startQueue() {
    if (this.loaded === false) return;
    if (this.running === true) return;
    if (this.queue.length === 0) return;
 
    this.running = true;
    await this.processJob();
    this.running = false;
  }
 
  async processJob() {
    const { task: taskRaw, annotation, resolve } = this.queue.shift();
 
    const task = {
      id: taskRaw.id,
      annotations: taskRaw.annotations,
      predictions: taskRaw.predictions,
      data: taskRaw.data,
    };
 
    this.lsf.resetState();
    this.lsf.assignTask(task);
    this.lsf.initializeStore(taskToLSFormat(task));
    this.lsf.annotationStore.selectAnnotation(annotation.pk ?? annotation.id);
 
    await wait(1500);
    const preview = await this.createPreviews(5);
 
    resolve(preview);
 
    if (this.queue.length) {
      await this.processJob();
    }
  }
 
  async createPreviews(attempts) {
    if (attempts === 0) return;
 
    try {
      return this.lsf.annotationStore.selected.generatePreviews();
    } catch (err) {
      await wait(1000);
      return this.createPreviews(attempts - 1);
    }
  }
}
 
const injector = inject(({ store }) => {
  return {
    labelingConfig: store?.labelingConfig,
  };
});
 
export const AnnotationPreview = injector(
  observer(({ labelingConfig, name, task, annotation, style, ...props }) => {
    const generator = React.useMemo(() => {
      if (labelingConfig) return PreviewGenerator.getInstance(labelingConfig);
    }, [labelingConfig]);
 
    const [preview, setPreview] = React.useState(null);
    const variant = props.variant ?? "original";
 
    React.useEffect(() => {
      if (preview !== null) return;
 
      const start = async () => {
        if (generator && task && annotation) {
          const preview = await generator.generatePreview(task, annotation);
 
          setPreview(preview);
        }
      };
 
      start();
    }, [task, annotation, generator, preview]);
 
    return preview ? (
      <img
        {...imgDefaultProps}
        src={preview[`$${name}`][variant]}
        alt=""
        style={style}
        width={props.width}
        height={props.height}
      />
    ) : (
      <div className={cn("annotation-preview").toString()} width={props.width} height={props.height}>
        <Spinner
          size={props.size ?? "default"}
          style={{
            position: "absolute",
            left: "50%",
            top: "50%",
            transform: "translate3d(-50%, -50%, 0)",
            zIndex: 100,
          }}
        />
        <img
          src={props.fallbackImage}
          style={{ ...(style ?? {}), opacity: 0.5 }}
          alt=""
          width={props.width}
          height={props.height}
        />
      </div>
    );
  }),
);