File size: 10,888 Bytes
2704918
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { useState, useEffect } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Loader2, Download, Check, AlertCircle, Brain, RefreshCw } from "lucide-react";
import { zipSync, strToU8 } from "fflate";
import type { NormalizedPost } from "@/lib/grabber/sites";

interface ImageDescriberModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  posts: NormalizedPost[];
}

export function ImageDescriberModal({ open, onOpenChange, posts }: ImageDescriberModalProps) {
  const [descriptions, setDescriptionState] = useState<
    Record<string, { text: string; loading: boolean; error?: string }>
  >({});
  const [downloadingZip, setDownloadingZip] = useState<Record<string, boolean>>({});

  useEffect(() => {
    if (!open) return;

    let active = true;
    const runDescriptions = async () => {
      for (const post of posts) {
        if (!active) break;
        
        // Skip if already generating or has description
        const currentState = descriptions[post.id];
        if (currentState && (currentState.text || currentState.loading)) {
          continue;
        }

        setDescriptionState((prev) => ({
          ...prev,
          [post.id]: { text: "", loading: true },
        }));

        try {
          const res = await fetch("/api/describe-image", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ imageUrl: post.fileUrl }),
          });
          const data = await res.json();
          if (!active) break;

          if (data.success && data.description) {
            setDescriptionState((prev) => ({
              ...prev,
              [post.id]: { text: data.description, loading: false },
            }));
          } else {
            setDescriptionState((prev) => ({
              ...prev,
              [post.id]: {
                text: "",
                loading: false,
                error: data.error || "Failed to generate description",
              },
            }));
          }
        } catch (err) {
          if (!active) break;
          setDescriptionState((prev) => ({
            ...prev,
            [post.id]: {
              text: "",
              loading: false,
              error: err instanceof Error ? err.message : "Inference error",
            },
          }));
        }
      }
    };

    runDescriptions();

    return () => {
      active = false;
    };
  }, [open, posts]);

  const handleDescribeSingle = async (post: NormalizedPost) => {
    setDescriptionState((prev) => ({
      ...prev,
      [post.id]: { text: "", loading: true, error: undefined },
    }));

    try {
      const res = await fetch("/api/describe-image", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ imageUrl: post.fileUrl }),
      });
      const data = await res.json();

      if (data.success && data.description) {
        setDescriptionState((prev) => ({
          ...prev,
          [post.id]: { text: data.description, loading: false },
        }));
      } else {
        setDescriptionState((prev) => ({
          ...prev,
          [post.id]: {
            text: "",
            loading: false,
            error: data.error || "Failed to generate description",
          },
        }));
      }
    } catch (err) {
      setDescriptionState((prev) => ({
        ...prev,
        [post.id]: {
          text: "",
          loading: false,
          error: err instanceof Error ? err.message : "Inference error",
        },
      }));
    }
  };

  const downloadSingleDescZip = async (post: NormalizedPost, description: string) => {
    setDownloadingZip((prev) => ({ ...prev, [post.id]: true }));
    try {
      const response = await fetch(post.fileUrl);
      if (!response.ok) throw new Error("Failed to fetch image file");
      const buffer = await response.arrayBuffer();
      const imgBytes = new Uint8Array(buffer);

      const zipFiles: Record<string, Uint8Array> = {};
      const ext = post.ext || "jpg";
      zipFiles[`image.${ext}`] = imgBytes;
      zipFiles[`desc.txt`] = strToU8(description);

      const zipped = zipSync(zipFiles, { level: 0 });
      const blob = new Blob([zipped], { type: "application/zip" });
      const url = URL.createObjectURL(blob);

      const a = document.createElement("a");
      a.href = url;
      a.download = `image_${post.id}_with_description.zip`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch (err) {
      alert(`Download failed: ${err instanceof Error ? err.message : "unknown error"}`);
    } finally {
      setDownloadingZip((prev) => ({ ...prev, [post.id]: false }));
    }
  };

  // Progress stats
  const describedCount = posts.filter((p) => descriptions[p.id]?.text).length;
  const loadingCount = posts.filter((p) => descriptions[p.id]?.loading).length;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl h-[90vh] flex flex-col p-6">
        <DialogHeader className="flex flex-row justify-between items-center border-b pb-4">
          <div>
            <DialogTitle className="text-xl font-bold flex items-center gap-2">
              <Brain className="w-5 h-5 text-purple-600 animate-pulse" />
              AI Image Describer (GGUF LLaVA)
            </DialogTitle>
            <DialogDescription className="text-xs text-muted-foreground mt-1">
              Described {describedCount} of {posts.length} selected images{" "}
              {loadingCount > 0 && "(Processing sequentially...)"}
            </DialogDescription>
          </div>
        </DialogHeader>

        <ScrollArea className="flex-1 pr-4 py-4">
          <div className="space-y-6">
            {posts.map((post) => {
              const state = descriptions[post.id] || { text: "", loading: false };
              const isZipping = downloadingZip[post.id];

              return (
                <div
                  key={post.id}
                  className="flex flex-col md:flex-row gap-4 p-4 rounded-lg border bg-muted/10 hover:bg-muted/20 transition"
                >
                  <div className="w-full md:w-48 h-48 rounded-md bg-muted overflow-hidden relative flex-shrink-0 flex items-center justify-center">
                    <img
                      src={post.previewUrl}
                      alt={`Post ${post.id}`}
                      className="w-full h-full object-cover"
                    />
                    <div className="absolute top-2 left-2 bg-black/60 text-white text-[10px] px-2 py-0.5 rounded font-mono">
                      ID: {post.id}
                    </div>
                  </div>

                  <div className="flex-1 flex flex-col justify-between min-w-0">
                    <div className="space-y-2">
                      <div className="flex items-center gap-2">
                        <span className="font-semibold text-sm uppercase text-muted-foreground">
                          Description
                        </span>
                        {state.loading && (
                          <span className="flex items-center gap-1 text-xs text-purple-600 font-medium">
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                            Analyzing image...
                          </span>
                        )}
                        {state.text && (
                          <span className="flex items-center gap-1 text-xs text-emerald-600 font-medium">
                            <Check className="w-3.5 h-3.5" />
                            Completed
                          </span>
                        )}
                        {state.error && (
                          <span className="flex items-center gap-1 text-xs text-destructive font-medium">
                            <AlertCircle className="w-3.5 h-3.5" />
                            Error: {state.error}
                          </span>
                        )}
                      </div>

                      <div className="text-sm text-foreground bg-muted/40 p-3 rounded-md min-h-[100px] whitespace-pre-wrap">
                        {state.loading && (
                          <div className="flex flex-col items-center justify-center h-16 text-muted-foreground gap-2">
                            <Loader2 className="w-6 h-6 animate-spin text-purple-600" />
                            <p className="text-xs">Running GGUF multimodal inference...</p>
                          </div>
                        )}
                        {!state.loading && !state.text && !state.error && (
                          <span className="text-muted-foreground italic">
                            Waiting in sequence queue...
                          </span>
                        )}
                        {state.error && (
                          <div className="flex flex-col gap-2">
                            <span className="text-destructive text-xs">{state.error}</span>
                            <Button
                              variant="outline"
                              size="sm"
                              className="w-24 text-xs h-8"
                              onClick={() => handleDescribeSingle(post)}
                            >
                              <RefreshCw className="w-3 h-3 mr-1" /> Retry
                            </Button>
                          </div>
                        )}
                        {state.text && <p className="leading-relaxed font-sans">{state.text}</p>}
                      </div>
                    </div>

                    {state.text && (
                      <div className="flex justify-end mt-4">
                        <Button
                          onClick={() => downloadSingleDescZip(post, state.text)}
                          disabled={isZipping}
                          size="sm"
                          className="bg-purple-600 hover:bg-purple-700 text-white font-medium text-xs h-9"
                        >
                          {isZipping ? (
                            <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" />
                          ) : (
                            <Download className="w-3.5 h-3.5 mr-1" />
                          )}
                          Download image.png + desc.txt
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        </ScrollArea>
      </DialogContent>
    </Dialog>
  );
}