File size: 6,087 Bytes
46861c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import React, { useContext, useEffect, useState } from "react";
import AppContext from "./hooks/createContext";
import { ToolProps, QueueStatus } from "./helpers/Interfaces";
import * as _ from "underscore";
import { describeMask, describeMaskWithoutStreaming } from "../services/maskApi";
import ErrorModal from './ErrorModal';
import { DescriptionState } from "./Stage";

const prompt = "<image>\nDescribe the masked region in detail.";

const Tool = ({ 
  handleMouseMove, 
  descriptionState, 
  setDescriptionState,
  queueStatus,
  setQueueStatus 
}: ToolProps) => {
  console.log("Tool handleMouseMove");
  const {
    image: [image],
    maskImg: [maskImg, setMaskImg],
    maskImgData: [maskImgData, setMaskImgData],
    isClicked: [isClicked, setIsClicked]
  } = useContext(AppContext)!;

  const [shouldFitToWidth, setShouldFitToWidth] = useState(true);
  const bodyEl = document.body;
  const fitToPage = () => {
    if (!image) return;
    const maxWidth = window.innerWidth - 64; // Account for padding (32px on each side)
    const maxHeight = window.innerHeight - 200; // Account for header and some padding
    const imageAspectRatio = image.width / image.height;
    const containerAspectRatio = maxWidth / maxHeight;
    
    setShouldFitToWidth(
      imageAspectRatio > containerAspectRatio || 
      image.width > maxWidth
    );
  };
  const resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      if (entry.target === bodyEl) {
        fitToPage();
      }
    }
  });
  useEffect(() => {
    fitToPage();
    resizeObserver.observe(bodyEl);
    return () => {
      resizeObserver.unobserve(bodyEl);
    };
  }, [image]);

  const imageClasses = "";
  const maskImageClasses = `absolute opacity-40 pointer-events-none`;

  const [error, setError] = useState<string | null>(null);
  const [useStreaming, setUseStreaming] = useState(true);

  useEffect(() => {
      if (!isClicked || !maskImg || !maskImgData || !image || descriptionState.state !== 'ready') {
        console.log("Not ready to call model, isClicked:", isClicked, "maskImg:", maskImg !== null, "maskImgData:", maskImgData !== null, "image:", image !== null, "descriptionState.state:", descriptionState.state);
        return;
      }

      try {
        setDescriptionState({
          state: 'describing',
          description: ''
        } as DescriptionState);

        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx = canvas.getContext('2d');
        ctx?.drawImage(image, 0, 0);
        const imageBase64 = canvas.toDataURL('image/jpeg').split(',')[1];
        const maskBase64 = maskImgData.split(',')[1];

        const describeMaskWithFallback = async (useStreamingInFunction: boolean) => {
          try {
            let result;
            console.log("useStreaming", useStreaming, "useStreamingInFunction", useStreamingInFunction);
            if (useStreamingInFunction) {
              result = await describeMask(
                maskBase64, 
                imageBase64,
                prompt,
                (streamResult: string) => {
                  setDescriptionState({
                    state: 'describing',
                    description: streamResult
                  } as DescriptionState);
                },
                (status: QueueStatus) => {
                  setQueueStatus(status);
                }
              );
            } else {
              result = await describeMaskWithoutStreaming(
                maskBase64,
                imageBase64,
                prompt
              );
            }
            
            setDescriptionState({
              state: 'described',
              description: result
            } as DescriptionState);
            setQueueStatus({ inQueue: false });
            setIsClicked(false);
          } catch (error) {
            if (useStreaming) {
              console.log("Error describing mask, switching to non-streaming", error);
              setUseStreaming(false);
              describeMaskWithFallback(false);
            } else {
              setError('Failed to generate description. Please try again.');
              setDescriptionState({
                state: 'ready',
                description: ''
              } as DescriptionState);
              setIsClicked(false);
              console.error('Failed to describe mask:', error);
            }
          }
        };

        describeMaskWithFallback(useStreaming);

      } catch (error) {
        setIsClicked(false);
        setError('Failed to generate description. Please try again.');
        setDescriptionState({
          state: 'ready',
          description: ''
        } as DescriptionState);
        console.error('Failed to describe mask:', error);
      }
  }, [maskImgData]);

  const handleClick = async (e: React.MouseEvent<HTMLImageElement>) => {
    if (descriptionState.state !== 'ready') return;
    
    setMaskImg(null);
    setMaskImgData(null);
    setIsClicked(true);
    handleMouseMove(e);
  };

  return (
    <>
      {error && <ErrorModal message={error} onClose={() => setError(null)} />}
      <div className="relative flex items-center justify-center w-full h-full">
        {image && (
          <img
            onMouseMove={handleMouseMove}
            onMouseLeave={() => _.defer(() => (descriptionState.state === 'ready' && !isClicked) ? setMaskImg(null) : undefined)}
            onTouchStart={handleMouseMove}
            onClick={handleClick}
            src={image.src}
            className={`${
              shouldFitToWidth ? "w-full" : "h-full"
            } ${imageClasses} object-contain max-h-full max-w-full`}
          ></img>
        )}
        {maskImg && (
          <img
            src={maskImg.src}
            className={`${
              shouldFitToWidth ? "w-full" : "h-full"
            } ${maskImageClasses} object-contain max-h-full max-w-full`}
          ></img>
        )}
      </div>
    </>
  );
};

export default Tool;