File size: 12,718 Bytes
624088c
 
 
f658021
624088c
 
932a7fd
 
 
 
624088c
 
932a7fd
f658021
797cbb8
932a7fd
5dd2af5
 
932a7fd
624088c
 
 
 
5dd2af5
 
 
 
 
 
 
932a7fd
5dd2af5
 
624088c
 
 
 
5dd2af5
 
 
 
 
 
 
 
 
f5d8038
719ed9c
797cbb8
932a7fd
 
f5d8038
932a7fd
d71abf1
932a7fd
5dd2af5
624088c
f658021
 
c32ec0d
5dd2af5
c32ec0d
82d85df
c32ec0d
82d85df
f5d8038
241036e
624088c
f5d8038
 
 
5dd2af5
f5d8038
7967a54
 
f5d8038
624088c
f5d8038
 
624088c
 
 
ae2cf82
5dd2af5
ae2cf82
5dd2af5
719ed9c
81eb27e
 
 
 
 
 
cb3fdda
624088c
cb3fdda
f5d8038
61bb967
 
f5d8038
624088c
cb3fdda
 
932a7fd
81eb27e
 
 
 
 
5dd2af5
81eb27e
 
 
 
 
726926f
 
81eb27e
 
 
 
 
 
 
 
 
 
726926f
 
81eb27e
 
 
 
 
 
726926f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7967a54
719ed9c
 
624088c
 
 
 
 
 
6b27fdb
624088c
 
7967a54
624088c
f5d8038
624088c
 
 
f5d8038
 
624088c
 
 
6b27fdb
5495410
 
6b27fdb
81eb27e
 
 
 
 
 
f5d8038
6b27fdb
f5d8038
 
6b27fdb
624088c
 
f5d8038
 
624088c
 
 
6b27fdb
624088c
 
 
7967a54
624088c
7967a54
 
81eb27e
7967a54
a79c634
 
624088c
 
 
 
 
 
7967a54
624088c
241036e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82d85df
c32ec0d
82d85df
974ed41
82d85df
974ed41
 
 
 
 
82d85df
 
a029993
82d85df
 
719ed9c
 
7967a54
719ed9c
cb3fdda
f658021
 
 
 
 
 
82d85df
932a7fd
 
82d85df
 
797cbb8
932a7fd
 
 
 
 
 
624088c
 
82d85df
932a7fd
624088c
719ed9c
 
 
 
fcdbd7f
c32ec0d
 
 
 
 
 
 
 
 
 
ec121fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5d8038
 
 
 
 
c32ec0d
b9e12dc
ec121fd
fcdbd7f
 
 
719ed9c
fcdbd7f
 
 
 
 
 
 
 
f3c09ed
 
 
 
67fda5f
f658021
719ed9c
 
 
 
 
67fda5f
719ed9c
 
 
 
 
67fda5f
719ed9c
67fda5f
719ed9c
f658021
 
 
 
 
 
 
 
 
67fda5f
f658021
 
 
 
 
67fda5f
f658021
67fda5f
f658021
 
 
719ed9c
f3c09ed
 
 
624088c
 
 
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"use client"

import { useEffect, useRef, useState, useTransition } from "react"
import { RxReload, RxPencil2 } from "react-icons/rx"

import { RenderedScene } from "@/types"

import { getRender, newRender } from "@/app/engine/render"
import { useStore } from "@/app/store"

import { cn } from "@/lib/utils"
import { getInitialRenderedScene } from "@/lib/getInitialRenderedScene"
import { Progress } from "@/app/interface/progress"
import { EditModal } from "../edit-modal"

export function Panel({
  page,
  nbPanels,
  panel,
  className = "",
  width = 1,
  height = 1,
}: {
  // page number of which the panel is
  page: number

  // the number of panels should be unique to each layout
  nbPanels: number

  // panel id, between 0 and (nbPanels - 1)
  panel: number


  className?: string
  width?: number
  height?: number
 }) {

  // index of the panel in the whole app
  const panelIndex = page * nbPanels + panel

  // console.log("debug:", { page, nbPanels, panel })
  // the panel Id must be unique across all pages
  const panelId = `${panelIndex}`

  // console.log("panelId: " + panelId)

  const [mouseOver, setMouseOver] = useState(false)
  const ref = useRef<HTMLImageElement>(null)
  const font = useStore(state => state.font)
  const preset = useStore(state => state.preset)

  const setGeneratingImages = useStore(state => state.setGeneratingImages)

  const panels = useStore(state => state.panels)
  const prompt = panels[panelIndex] || ""

  const setPanelPrompt = useStore(state => state.setPanelPrompt)

  const captions = useStore(state => state.captions)
  const caption = captions[panelIndex] || ""

  const zoomLevel = useStore(state => state.zoomLevel)
  const showCaptions = useStore(state => state.showCaptions)

  const addToUpscaleQueue = useStore(state => state.addToUpscaleQueue)

  const [_isPending, startTransition] = useTransition()
  const renderedScenes = useStore(state => state.renderedScenes)
  const setRendered = useStore(state => state.setRendered)

  const rendered = renderedScenes[panelIndex] || getInitialRenderedScene()

  const [revision, setRevision] = useState(0)

  // keep a ref in sync
  const renderedRef = useRef<RenderedScene>()
  const renderedKey = JSON.stringify(rendered)
  useEffect(() => { renderedRef.current = rendered }, [renderedKey])

  const timeoutRef = useRef<any>(null)

  const enableRateLimiter = `${process.env.NEXT_PUBLIC_ENABLE_RATE_LIMITER}`  === "true"
 

  const delay = enableRateLimiter ? (1000 + (500 * panelIndex)) : 1000

  const startImageGeneration = ({ prompt, width, height, revision }: {
    prompt: string
    width: number
    height: number
    revision: number
  }) => {
    if (!prompt?.length) { return }

    // important: update the status, and clear the scene
    setGeneratingImages(panelId, true)

    // just to empty it
    setRendered(panelId, getInitialRenderedScene())

    setTimeout(() => {
      startTransition(async () => {

        const withCache = revision === 0

        // atrocious and very, very, very, very, very, very, very ugly hack for the Inference API
        // as apparently "use_cache: false" doesn't work, or doesn't do what we want it to do
        let cacheInvalidationHack = ""
        const nbMaxRevisions = 10
        for (let i = 0; i < revision && revision < nbMaxRevisions; i++) {
          const j =  Math.random() 
          cacheInvalidationHack += j < 0.3 ? "_" : j < 0.6 ? "," : "-"
        }

        let newRendered: RenderedScene
        try {
  
          newRendered = await newRender({
            prompt: cacheInvalidationHack + " " + prompt,
            width,
            height,

            // TODO: here we never reset the revision, so only the first user
            // comic will be cached (we should fix that later)
            withCache: revision === 0
          })
        } catch (err) {
          // "Failed to load the panel! Don't worry, we are retrying..")
          newRendered = await newRender({
            prompt: cacheInvalidationHack + "   " + prompt,
            width,
            height,
            withCache,
          })
        }

        if (newRendered) {
          setRendered(panelId, newRendered)

          if (newRendered.status === "completed") {
            setGeneratingImages(panelId, false)
            addToUpscaleQueue(panelId, newRendered)
          }

          // but we are still loading!
        } else {
          setRendered(panelId, {
            renderId: "",
            status: "pending",
            assetUrl: "",
            alt: "",
            maskUrl: "",
            error: "",
            segments: []
          })
          setGeneratingImages(panelId, false)
          return
        }
      })
    }, enableRateLimiter ? 1000 * panel : 0)
  }


  const checkStatus = () => {
    startTransition(async () => {
      clearTimeout(timeoutRef.current)

      if (!renderedRef.current?.renderId || renderedRef.current?.status !== "pending") {
        timeoutRef.current = setTimeout(checkStatus, delay)
        return
      }

      try {
        setGeneratingImages(panelId, true)
        const newRendered = await getRender(renderedRef.current.renderId)

        if (JSON.stringify(renderedRef.current) !== JSON.stringify(newRendered)) {
          setRendered(panelId, renderedRef.current = newRendered)
          setGeneratingImages(panelId, true)
        }

        if (newRendered.status === "pending") {
          timeoutRef.current = setTimeout(checkStatus, delay)
        } else if (newRendered.status === "error" || 
        (newRendered.status === "completed" && !newRendered.assetUrl?.length)) {
          try {
            const newAttempt = await newRender({
              prompt,
              width,
              height,
              withCache: false,
            })
            setRendered(panelId, newAttempt)
          } catch (err) {
            console.error("yeah sorry, something is wrong.. aborting", err)
            setGeneratingImages(panelId, false)
          }
        } else {
          console.log("panel finished!")
          setGeneratingImages(panelId, false)
          addToUpscaleQueue(panelId, newRendered)
        }
      } catch (err) {
        console.error(err)
        timeoutRef.current = setTimeout(checkStatus, delay)
      }
    })
  }

  useEffect(() => {
    if (!prompt.length) { return }

    startImageGeneration({ prompt, width, height, revision })

    clearTimeout(timeoutRef.current)
    
    // normally it should reply in < 1sec, but we could also use an interval
    timeoutRef.current = setTimeout(checkStatus, delay)

    return () => {
      clearTimeout(timeoutRef.current)
    }
  }, [prompt, width, height, revision])

  /*
  doing the captionning from the browser is expensive
  a simpler solution is to caption directly during SDXL generation

  useEffect(() => {
    if (!rendered.assetUrl) { return }
    // the asset url can evolve with time (link to a better resolution image)
    // however it would be costly to ask for the caption, the low resolution is enough for the semantic resolution
    // so we just do nothing if we already have the caption
    if (caption) { return }
    startTransition(async () => {
      try {
        const newCaption = await see({
          prompt: "please caption the following image",
          imageBase64: rendered.assetUrl 
        })
        if (newCaption) {
          setCaption(newCaption)
        }
      } catch (err) {
        console.error(`failed to generate the caption:`, err)
      }
    })
  }, [rendered.assetUrl, caption])
  */

  const frameClassName = cn(
    //`flex`,
    `w-full h-full`,
    `border-stone-800`,
    `transition-all duration-200 ease-in-out`,
    zoomLevel > 140 ? `border-[2px] md:border-[4px] rounded-sm md:rounded-md` :
    zoomLevel > 120 ? `border-[1.5px] md:border-[3px] rounded-xs md:rounded-sm` :
    zoomLevel > 90 ? `border-[1px] md:border-[2px] rounded-xs md:rounded-sm` :
    zoomLevel > 40 ? `border-[0.5px] md:border-[1px] rounded-none md:rounded-xs` :
    `border-transparent md:border-[0.5px] rounded-none md:rounded-none`,
    `shadow-sm`,
    `overflow-hidden`,
    `print:border-[1.5px] print:shadow-none`,
  )

  const handleReload = () => {
    console.log(`Asked to reload panel ${panelId}`)
    setRevision(revision + 1)
  }


  const handleSavePrompt = (newPrompt: string) => {
    console.log(`Asked to save a new prompt: ${newPrompt}`)
    setPanelPrompt(newPrompt, panelIndex)
  }

  if (prompt && !rendered.assetUrl) {
    return (
      <div className={cn(
        frameClassName,
        `flex flex-col items-center justify-center`,
        className,
      )}>
       <Progress isLoading />
      </div>
    )
  }

  return (
    <div className={cn(
      frameClassName,
      { "grayscale": preset.color === "grayscale" },
      className
    )}
    onMouseEnter={() => setMouseOver(true)}
    onMouseLeave={() => setMouseOver(false)}
    >
        <div className={cn(
        `bg-stone-50`,
        `border-stone-800`,
        `transition-all duration-200 ease-in-out`,
        zoomLevel > 140 ? `border-b-[2px] md:border-b-[4px]` :
        zoomLevel > 120 ? `border-b-[1.5px] md:border-b-[3px]` :
        zoomLevel > 90 ? `border-b-[1px] md:border-b-[2px]` :
        zoomLevel > 40 ? `border-b-[0.5px] md:border-b-[1px]` :
        `border-transparent md:border-b-[0.5px]`,
        `print:border-b-[1.5px]`,
        `truncate`,

        zoomLevel > 200 ? `p-4 md:p-8` :
        zoomLevel > 180 ? `p-[14px] md:p-8` :
        zoomLevel > 160 ? `p-[12px] md:p-[28px]` :
        zoomLevel > 140 ? `p-[10px] md:p-[26px]` :
        zoomLevel > 120 ? `p-2 md:p-6` :
        zoomLevel > 100 ? `p-1.5 md:p-[20px]` :
        zoomLevel > 90 ? `p-1.5 md:p-4` :
        zoomLevel > 40 ? `p-1 md:p-2` :
        `p-0.5 md:p-2`,

        zoomLevel > 220 ? `text-xl md:text-4xl` :
        zoomLevel > 200 ? `text-lg md:text-3xl` :
        zoomLevel > 180 ? `text-md md:text-2xl` :
        zoomLevel > 140 ? `text-2xs md:text-2xl` :
        zoomLevel > 120 ? `text-3xs md:text-xl` :
        zoomLevel > 100 ? `text-4xs md:text-lg` :
        zoomLevel > 90 ? `text-5xs md:text-sm` :
        zoomLevel > 40 ? `md:text-xs` : `md:text-2xs`,

        showCaptions ? (
          zoomLevel > 90 ? `block` : `hidden md:block`
        ) : `hidden`,
      )}
      >{caption || ""}
        </div>
        {rendered.assetUrl &&
        <img
          ref={ref}
          src={rendered.assetUrl}
          width={width}
          height={height}
          alt={rendered.alt}
          className={cn(
            `comic-panel w-full h-full object-cover max-w-max`,
            // showCaptions ? `-mt-11` : ''
            )}
        />}
        {
          // there is an issue, this env check doesn't work..
        // process.env.NEXT_PUBLIC_CAN_REDRAW === "true" ?
         <div
        className={cn(`relative -mt-8 ml-2 md:-mt-12md:ml-3 lg:-mt-14 lg:ml-4`,)}>
          <div className="flex flex-row space-x-2">
            <div
              onClick={rendered.status === "completed" ? handleReload : undefined}
              className={cn(
                `bg-stone-100 rounded-lg`,
                `flex flex-row space-x-2 items-center`,
                `py-1 px-2 md:py-2 md:px-3 cursor-pointer`,
                `transition-all duration-200 ease-in-out`,
                rendered.status === "completed" ? "opacity-95" : "opacity-50",
                mouseOver && rendered.assetUrl ? `scale-95 hover:scale-100 hover:opacity-100`: `scale-0`
              )}>
              <RxReload
                className="w-3 h-3 md:w-4 md:h-4 lg:w-5 lg:h-5"
              />
              <span className="text-2xs md:text-xs lg:text-sm">Redraw</span>
            </div>
            <EditModal
              isEnabled={rendered.status === "completed"}
              existingPrompt={prompt}
              onSave={handleSavePrompt}
            >
              <div
                className={cn(
                  `bg-stone-100 rounded-lg`,
                  `flex flex-row space-x-2 items-center`,
                  `py-1 px-3 md:py-2 md:px-3 cursor-pointer`,
                  `transition-all duration-200 ease-in-out`,
                  rendered.status === "completed" ? "opacity-95" : "opacity-50",
                  mouseOver && rendered.assetUrl ? `scale-95 hover:scale-100 hover:opacity-100`: `scale-0`
                )}>
                <RxPencil2
                  className="w-3 h-3 md:w-4 md:h-4 lg:w-5 lg:h-5"
                />
                <span className="text-2xs md:text-xs lg:text-sm">Edit</span>
              </div>
                        
            </EditModal>
          </div>
        </div> 
        //: null
      }
    </div>
  )
}