page.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. "use client";
  2. import { useState, useEffect } from "react";
  3. import { Header, AppLayout } from "@/components/layout";
  4. import { Button } from "@/components/ui/button";
  5. import { Input } from "@/components/ui/input";
  6. import { PromptTextarea } from "@/components/forms";
  7. import { Label } from "@/components/ui/label";
  8. import { Card, CardContent } from "@/components/ui/card";
  9. import { ImageInput } from "@/components/ui/image-input";
  10. import {
  11. Select,
  12. SelectContent,
  13. SelectItem,
  14. SelectTrigger,
  15. SelectValue,
  16. } from "@/components/ui/select";
  17. import { apiClient, type JobInfo, type JobDetailsResponse } from "@/lib/api";
  18. import {
  19. downloadImage,
  20. downloadAuthenticatedImage,
  21. fileToBase64,
  22. } from "@/lib/utils";
  23. import { useLocalStorage, useMemoryStorage, useGeneratedImages } from "@/lib/storage";
  24. import { useModelTypeSelection } from "@/contexts/model-selection-context";
  25. import { type ImageValidationResult } from "@/lib/image-validation";
  26. import { Loader2, Download, X } from "lucide-react";
  27. type Img2ImgFormData = {
  28. prompt: string;
  29. negative_prompt: string;
  30. image: string;
  31. strength: number;
  32. steps: number;
  33. cfg_scale: number;
  34. seed: string;
  35. sampling_method: string;
  36. width?: number;
  37. height?: number;
  38. };
  39. const defaultFormData: Img2ImgFormData = {
  40. prompt: "",
  41. negative_prompt: "",
  42. image: "",
  43. strength: 0.75,
  44. steps: 20,
  45. cfg_scale: 7.5,
  46. seed: "",
  47. sampling_method: "euler_a",
  48. width: 512,
  49. height: 512,
  50. };
  51. function Img2ImgForm() {
  52. const {
  53. availableModels: vaeModels,
  54. selectedModel: selectedVae,
  55. setSelectedModel: setSelectedVae,
  56. } = useModelTypeSelection("vae");
  57. const {
  58. availableModels: taesdModels,
  59. selectedModel: selectedTaesd,
  60. setSelectedModel: setSelectedTaesd,
  61. } = useModelTypeSelection("taesd");
  62. // Store form data without the image to avoid localStorage quota issues
  63. const { ...formDataWithoutImage } = defaultFormData;
  64. const [formData, setFormData] = useLocalStorage<
  65. Omit<Img2ImgFormData, "image">
  66. >("img2img-form-data", formDataWithoutImage);
  67. // Store image separately in memory
  68. const [imageData, setImageData] = useMemoryStorage<string>("");
  69. // Combined form data with image
  70. const fullFormData = { ...formData, image: imageData };
  71. const [loading, setLoading] = useState(false);
  72. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  73. const { images: storedImages, addImages, getLatestImages } = useGeneratedImages('img2img');
  74. const [generatedImages, setGeneratedImages] = useState<string[]>(() => getLatestImages());
  75. const [loraModels, setLoraModels] = useState<string[]>([]);
  76. const [embeddings, setEmbeddings] = useState<string[]>([]);
  77. const [selectedImage, setSelectedImage] = useState<File | string | null>(
  78. null,
  79. );
  80. const [imageValidation, setImageValidation] =
  81. useState<ImageValidationResult | null>(null);
  82. const [originalImage, setOriginalImage] = useState<string | null>(null);
  83. const [isResizing, setIsResizing] = useState(false);
  84. const [error, setError] = useState<string | null>(null);
  85. const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null);
  86. const [imageLoadingFromUrl, setImageLoadingFromUrl] = useState(false);
  87. // Cleanup polling on unmount
  88. useEffect(() => {
  89. return () => {
  90. if (pollCleanup) {
  91. pollCleanup();
  92. }
  93. };
  94. }, [pollCleanup]);
  95. useEffect(() => {
  96. const loadModels = async () => {
  97. try {
  98. const [loras, embeds] = await Promise.all([
  99. apiClient.getModels("lora"),
  100. apiClient.getModels("embedding"),
  101. ]);
  102. setLoraModels(loras.models.map((m) => m.name));
  103. setEmbeddings(embeds.models.map((m) => m.name));
  104. } catch (err) {
  105. console.error("Failed to load models:", err);
  106. }
  107. };
  108. loadModels();
  109. }, []);
  110. const handleInputChange = (
  111. e: React.ChangeEvent<
  112. HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
  113. >,
  114. ) => {
  115. const { name, value } = e.target;
  116. setFormData((prev) => ({
  117. ...prev,
  118. [name]:
  119. name === "prompt" ||
  120. name === "negative_prompt" ||
  121. name === "seed" ||
  122. name === "sampling_method"
  123. ? value
  124. : Number(value),
  125. }));
  126. };
  127. const handleImageChange = async (image: File | string | null) => {
  128. setSelectedImage(image);
  129. setError(null);
  130. if (!image) {
  131. setImageData("");
  132. setFormData((prev) => ({ ...prev, image: "" }));
  133. setImageValidation(null);
  134. setOriginalImage(null);
  135. return;
  136. }
  137. try {
  138. let imageBase64: string;
  139. if (image instanceof File) {
  140. // Convert File to base64
  141. imageBase64 = await fileToBase64(image);
  142. } else {
  143. // For URLs, don't set preview immediately - wait for validation
  144. // The validation will provide base64 data for preview and processing
  145. imageBase64 = ""; // Will be set by validation
  146. // previewUrl = null; // Will be set by validation
  147. setImageLoadingFromUrl(true);
  148. console.log(
  149. "Image URL provided, waiting for validation to process:",
  150. image,
  151. );
  152. }
  153. // Store original image for resizing (will be updated by validation if URL)
  154. if (image instanceof File) {
  155. setOriginalImage(imageBase64);
  156. setImageData(imageBase64);
  157. ;
  158. }
  159. setFormData((prev) => ({ ...prev })); // Don't store image in localStorage
  160. } catch (err) {
  161. setError("Failed to process image");
  162. console.error("Image processing error:", err);
  163. }
  164. };
  165. // Auto-resize image when width or height changes, but only if we have valid image data
  166. useEffect(() => {
  167. const resizeImage = async () => {
  168. if (!originalImage || !formData.width || !formData.height) {
  169. return;
  170. }
  171. // Don't resize if we're already resizing or still loading from URL
  172. if (isResizing || imageLoadingFromUrl) {
  173. return;
  174. }
  175. // Check if we have valid image data (data URL or HTTP URL)
  176. const isValidImageData =
  177. originalImage.startsWith("data:image/") ||
  178. originalImage.startsWith("http://") ||
  179. originalImage.startsWith("https://");
  180. if (!isValidImageData) {
  181. console.warn(
  182. "Invalid image data format for resizing:",
  183. originalImage.substring(0, 50),
  184. );
  185. return; // Don't show error for timing issues, just skip resize
  186. }
  187. try {
  188. setIsResizing(true);
  189. console.log(
  190. "Attempting to resize image, data type:",
  191. originalImage.startsWith("data:image/") ? "data URL" : "HTTP URL",
  192. );
  193. console.log("Image data length:", originalImage.length);
  194. console.log("Resize dimensions:", formData.width, "x", formData.height);
  195. const result = await apiClient.resizeImage(
  196. originalImage,
  197. formData.width,
  198. formData.height,
  199. );
  200. setImageData(result.image);
  201. setFormData((prev) => ({ ...prev })); // Don't store image in localStorage
  202. ;
  203. } catch (err) {
  204. console.error("Failed to resize image:", err);
  205. const errorMessage =
  206. err instanceof Error ? err.message : "Unknown error";
  207. setError(
  208. `Failed to resize image: ${errorMessage}. You may need to resize the image manually or use different dimensions.`,
  209. );
  210. } finally {
  211. setIsResizing(false);
  212. }
  213. };
  214. resizeImage();
  215. }, [
  216. formData.width,
  217. formData.height,
  218. originalImage,
  219. imageLoadingFromUrl,
  220. isResizing,
  221. setFormData,
  222. setImageData,
  223. ]);
  224. const handleImageValidation = (result: ImageValidationResult) => {
  225. setImageValidation(result);
  226. setImageLoadingFromUrl(false);
  227. if (!result.isValid) {
  228. setError(result.error || "Invalid image");
  229. } else {
  230. setError(null);
  231. // If we have temporary URL or base64 data from URL download, use it for preview and processing
  232. if (selectedImage && typeof selectedImage === "string") {
  233. if (result.tempUrl) {
  234. // Use temporary URL for preview and processing
  235. const fullTempUrl = result.tempUrl.startsWith("/")
  236. ? `${window.location.origin}${result.tempUrl}`
  237. : result.tempUrl;
  238. ;
  239. setOriginalImage(fullTempUrl);
  240. // For processing, we still need to convert to base64 or use the URL directly
  241. // The resize endpoint can handle URLs, so we can use the temp URL
  242. setImageData(fullTempUrl);
  243. console.log(
  244. "Using temporary URL from URL validation for image processing:",
  245. fullTempUrl,
  246. );
  247. console.log("Temporary filename:", result.tempFilename);
  248. } else if (result.base64Data) {
  249. // Fallback to base64 data if no temporary URL
  250. if (
  251. result.base64Data.startsWith("data:image/") &&
  252. result.base64Data.includes("base64,")
  253. ) {
  254. ;
  255. setImageData(result.base64Data);
  256. setOriginalImage(result.base64Data);
  257. console.log(
  258. "Using base64 data from URL validation for image processing",
  259. );
  260. console.log("Base64 data length:", result.base64Data.length);
  261. console.log(
  262. "Base64 data preview:",
  263. result.base64Data.substring(0, 100) + "...",
  264. );
  265. } else {
  266. console.error(
  267. "Invalid base64 data format received from server:",
  268. result.base64Data.substring(0, 100),
  269. );
  270. setError("Invalid image data format received from server");
  271. }
  272. }
  273. }
  274. }
  275. };
  276. const pollJobStatus = async (jobId: string) => {
  277. const maxAttempts = 300;
  278. let attempts = 0;
  279. let isPolling = true;
  280. let timeoutId: NodeJS.Timeout | null = null;
  281. const poll = async () => {
  282. if (!isPolling) return;
  283. try {
  284. const status: JobDetailsResponse = await apiClient.getJobStatus(jobId);
  285. setJobInfo(status.job);
  286. if (status.job.status === "completed") {
  287. let imageUrls: string[] = [];
  288. // Handle both old format (result.images) and new format (outputs)
  289. if (status.job.outputs && status.job.outputs.length > 0) {
  290. // New format: convert output URLs to authenticated image URLs with cache-busting
  291. imageUrls = status.job.outputs.map((output: { filename: string }) => {
  292. const filename = output.filename;
  293. return apiClient.getImageUrl(jobId, filename);
  294. });
  295. } else if (
  296. status.job.result?.images &&
  297. status.job.result.images.length > 0
  298. ) {
  299. // Old format: convert image URLs to authenticated URLs
  300. imageUrls = status.job.result.images.map((imageUrl: string) => {
  301. // Extract filename from URL if it's already a full URL
  302. if (imageUrl.includes("/output/")) {
  303. const parts = imageUrl.split("/output/");
  304. if (parts.length === 2) {
  305. const filename = parts[1].split("?")[0]; // Remove query params
  306. return apiClient.getImageUrl(jobId, filename);
  307. }
  308. }
  309. // If it's just a filename, convert it directly
  310. return apiClient.getImageUrl(jobId, imageUrl);
  311. });
  312. }
  313. // Create a new array to trigger React re-render
  314. setGeneratedImages([...imageUrls]);
  315. addImages(imageUrls, jobId);
  316. setLoading(false);
  317. isPolling = false;
  318. } else if (status.job.status === "failed") {
  319. setError(status.job.error || "Generation failed");
  320. setLoading(false);
  321. isPolling = false;
  322. } else if (status.job.status === "cancelled") {
  323. setError("Generation was cancelled");
  324. setLoading(false);
  325. isPolling = false;
  326. } else if (attempts < maxAttempts) {
  327. attempts++;
  328. timeoutId = setTimeout(poll, 2000);
  329. } else {
  330. setError("Job polling timeout");
  331. setLoading(false);
  332. isPolling = false;
  333. }
  334. } catch (err) {
  335. if (isPolling) {
  336. setError(
  337. err instanceof Error ? err.message : "Failed to check job status",
  338. );
  339. setLoading(false);
  340. isPolling = false;
  341. }
  342. }
  343. };
  344. poll();
  345. // Return cleanup function
  346. return () => {
  347. isPolling = false;
  348. if (timeoutId) {
  349. clearTimeout(timeoutId);
  350. }
  351. };
  352. };
  353. const handleGenerate = async (e: React.FormEvent) => {
  354. e.preventDefault();
  355. if (!fullFormData.image) {
  356. setError("Please upload or select an image first");
  357. return;
  358. }
  359. // Check if image validation passed
  360. if (imageValidation && !imageValidation.isValid) {
  361. setError("Please fix the image validation errors before generating");
  362. return;
  363. }
  364. setLoading(true);
  365. setError(null);
  366. setGeneratedImages([]);
  367. setJobInfo(null);
  368. try {
  369. const requestData = {
  370. ...fullFormData,
  371. vae: selectedVae || undefined,
  372. taesd: selectedTaesd || undefined,
  373. };
  374. const job = await apiClient.img2img(requestData);
  375. setJobInfo(job);
  376. const jobId = job.request_id || job.id;
  377. if (jobId) {
  378. const cleanup = pollJobStatus(jobId);
  379. setPollCleanup(() => cleanup);
  380. } else {
  381. setError("No job ID returned from server");
  382. setLoading(false);
  383. }
  384. } catch (err) {
  385. setError(err instanceof Error ? err.message : "Failed to generate image");
  386. setLoading(false);
  387. }
  388. };
  389. const handleCancel = async () => {
  390. const jobId = jobInfo?.request_id || jobInfo?.id;
  391. if (jobId) {
  392. try {
  393. await apiClient.cancelJob(jobId);
  394. setLoading(false);
  395. setError("Generation cancelled");
  396. // Cleanup polling
  397. if (pollCleanup) {
  398. pollCleanup();
  399. setPollCleanup(null);
  400. }
  401. } catch (err) {
  402. console.error("Failed to cancel job:", err);
  403. }
  404. }
  405. };
  406. return (
  407. <AppLayout>
  408. <Header
  409. title="Image to Image"
  410. description="Transform images with AI using text prompts"
  411. />
  412. <div className="container mx-auto p-6">
  413. <div className="grid gap-6 lg:grid-cols-2">
  414. {/* Left Panel - Form */}
  415. <Card>
  416. <CardContent className="pt-6">
  417. <form onSubmit={handleGenerate} className="space-y-4">
  418. <div className="space-y-2">
  419. <Label>Source Image *</Label>
  420. <ImageInput
  421. value={selectedImage}
  422. onChange={handleImageChange}
  423. onValidation={handleImageValidation}
  424. disabled={loading}
  425. maxSize={10 * 1024 * 1024} // 10MB
  426. accept="image/*"
  427. placeholder="Enter image URL or select a file"
  428. showPreview={true}
  429. />
  430. </div>
  431. <div className="space-y-2">
  432. <Label htmlFor="prompt">Prompt *</Label>
  433. <PromptTextarea
  434. value={formData.prompt}
  435. onChange={(value) =>
  436. setFormData({ ...formData, prompt: value })
  437. }
  438. placeholder="Describe the transformation you want..."
  439. rows={3}
  440. loras={loraModels}
  441. embeddings={embeddings}
  442. />
  443. <p className="text-xs text-muted-foreground">
  444. Tip: Use &lt;lora:name:weight&gt; for LoRAs and embedding
  445. names directly
  446. </p>
  447. </div>
  448. <div className="space-y-2">
  449. <Label htmlFor="negative_prompt">Negative Prompt</Label>
  450. <PromptTextarea
  451. value={formData.negative_prompt || ""}
  452. onChange={(value) =>
  453. setFormData({ ...formData, negative_prompt: value })
  454. }
  455. placeholder="What to avoid..."
  456. rows={2}
  457. loras={loraModels}
  458. embeddings={embeddings}
  459. />
  460. </div>
  461. <div className="space-y-2">
  462. <Label htmlFor="strength">
  463. Strength: {formData.strength.toFixed(2)}
  464. </Label>
  465. <Input
  466. id="strength"
  467. name="strength"
  468. type="range"
  469. value={formData.strength}
  470. onChange={handleInputChange}
  471. min={0}
  472. max={1}
  473. step={0.05}
  474. />
  475. <p className="text-xs text-muted-foreground">
  476. Lower values preserve more of the original image
  477. </p>
  478. </div>
  479. <div className="grid grid-cols-2 gap-4">
  480. <div className="space-y-2">
  481. <Label htmlFor="width">Width</Label>
  482. <Input
  483. id="width"
  484. name="width"
  485. type="number"
  486. value={formData.width}
  487. onChange={handleInputChange}
  488. step={64}
  489. min={256}
  490. max={2048}
  491. disabled={isResizing}
  492. />
  493. </div>
  494. <div className="space-y-2">
  495. <Label htmlFor="height">Height</Label>
  496. <Input
  497. id="height"
  498. name="height"
  499. type="number"
  500. value={formData.height}
  501. onChange={handleInputChange}
  502. step={64}
  503. min={256}
  504. max={2048}
  505. disabled={isResizing}
  506. />
  507. </div>
  508. </div>
  509. {isResizing && (
  510. <div className="text-sm text-muted-foreground flex items-center gap-2">
  511. <Loader2 className="h-4 w-4 animate-spin" />
  512. Resizing image...
  513. </div>
  514. )}
  515. <div className="grid grid-cols-2 gap-4">
  516. <div className="space-y-2">
  517. <Label htmlFor="steps">Steps</Label>
  518. <Input
  519. id="steps"
  520. name="steps"
  521. type="number"
  522. value={formData.steps}
  523. onChange={handleInputChange}
  524. min={1}
  525. max={150}
  526. />
  527. </div>
  528. <div className="space-y-2">
  529. <Label htmlFor="cfg_scale">CFG Scale</Label>
  530. <Input
  531. id="cfg_scale"
  532. name="cfg_scale"
  533. type="number"
  534. value={formData.cfg_scale}
  535. onChange={handleInputChange}
  536. step={0.5}
  537. min={1}
  538. max={30}
  539. />
  540. </div>
  541. </div>
  542. <div className="space-y-2">
  543. <Label htmlFor="seed">Seed (optional)</Label>
  544. <Input
  545. id="seed"
  546. name="seed"
  547. value={formData.seed}
  548. onChange={handleInputChange}
  549. placeholder="Leave empty for random"
  550. />
  551. </div>
  552. <div className="space-y-2">
  553. <Label htmlFor="sampling_method">Sampling Method</Label>
  554. <select
  555. id="sampling_method"
  556. name="sampling_method"
  557. value={formData.sampling_method}
  558. onChange={handleInputChange}
  559. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  560. >
  561. <option value="euler">Euler</option>
  562. <option value="euler_a">Euler A</option>
  563. <option value="heun">Heun</option>
  564. <option value="dpm2">DPM2</option>
  565. <option value="dpm++2s_a">DPM++ 2S A</option>
  566. <option value="dpm++2m">DPM++ 2M</option>
  567. <option value="dpm++2mv2">DPM++ 2M V2</option>
  568. <option value="lcm">LCM</option>
  569. </select>
  570. </div>
  571. <div className="space-y-2">
  572. <Label>VAE Model (Optional)</Label>
  573. <Select
  574. value={selectedVae || "none"}
  575. onValueChange={(value) => setSelectedVae(value === "none" ? undefined : value)}
  576. >
  577. <SelectTrigger>
  578. <SelectValue placeholder="Select VAE model" />
  579. </SelectTrigger>
  580. <SelectContent>
  581. <SelectItem value="none">None</SelectItem>
  582. {vaeModels.map((model) => {
  583. const modelId = model.sha256_short || model.sha256 || model.id || model.name;
  584. const displayName = model.sha256_short
  585. ? `${model.name} (${model.sha256_short})`
  586. : model.name;
  587. return (
  588. <SelectItem key={modelId} value={modelId}>
  589. {displayName}
  590. </SelectItem>
  591. );
  592. })}
  593. </SelectContent>
  594. </Select>
  595. </div>
  596. <div className="space-y-2">
  597. <Label>TAESD Model (Optional)</Label>
  598. <Select
  599. value={selectedTaesd || "none"}
  600. onValueChange={(value) => setSelectedTaesd(value === "none" ? undefined : value)}
  601. >
  602. <SelectTrigger>
  603. <SelectValue placeholder="Select TAESD model" />
  604. </SelectTrigger>
  605. <SelectContent>
  606. <SelectItem value="none">None</SelectItem>
  607. {taesdModels.map((model) => {
  608. const modelId = model.sha256_short || model.sha256 || model.id || model.name;
  609. const displayName = model.sha256_short
  610. ? `${model.name} (${model.sha256_short})`
  611. : model.name;
  612. return (
  613. <SelectItem key={modelId} value={modelId}>
  614. {displayName}
  615. </SelectItem>
  616. );
  617. })}
  618. </SelectContent>
  619. </Select>
  620. </div>
  621. <div className="flex gap-2">
  622. <Button
  623. type="submit"
  624. disabled={
  625. loading ||
  626. !imageData ||
  627. imageValidation?.isValid === false
  628. }
  629. className="flex-1"
  630. >
  631. {loading ? (
  632. <>
  633. <Loader2 className="h-4 w-4 animate-spin" />
  634. Generating...
  635. </>
  636. ) : (
  637. "Generate"
  638. )}
  639. </Button>
  640. {loading && (
  641. <Button
  642. type="button"
  643. variant="destructive"
  644. onClick={handleCancel}
  645. >
  646. <X className="h-4 w-4" />
  647. Cancel
  648. </Button>
  649. )}
  650. </div>
  651. {error && (
  652. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  653. {error}
  654. </div>
  655. )}
  656. </form>
  657. </CardContent>
  658. </Card>
  659. {/* Right Panel - Generated Images */}
  660. <Card>
  661. <CardContent className="pt-6">
  662. <div className="space-y-4">
  663. <h3 className="text-lg font-semibold">Generated Images</h3>
  664. {generatedImages.length === 0 ? (
  665. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  666. <p className="text-muted-foreground">
  667. {loading
  668. ? "Generating..."
  669. : "Generated images will appear here"}
  670. </p>
  671. </div>
  672. ) : (
  673. <div className="grid gap-4">
  674. {generatedImages.map((image, index) => (
  675. <div key={index} className="relative group">
  676. <img
  677. src={image}
  678. alt={`Generated ${index + 1}`}
  679. className="w-full rounded-lg border border-border"
  680. />
  681. <Button
  682. size="icon"
  683. variant="secondary"
  684. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  685. onClick={() => {
  686. const authToken =
  687. localStorage.getItem("auth_token");
  688. const unixUser = localStorage.getItem("unix_user");
  689. downloadAuthenticatedImage(
  690. image,
  691. `img2img-${Date.now()}-${index}.png`,
  692. authToken || undefined,
  693. unixUser || undefined,
  694. ).catch((err) => {
  695. console.error("Failed to download image:", err);
  696. // Fallback to regular download if authenticated download fails
  697. downloadImage(
  698. image,
  699. `img2img-${Date.now()}-${index}.png`,
  700. );
  701. });
  702. }}
  703. >
  704. <Download className="h-4 w-4" />
  705. </Button>
  706. </div>
  707. ))}
  708. </div>
  709. )}
  710. </div>
  711. </CardContent>
  712. </Card>
  713. </div>
  714. </div>
  715. </AppLayout>
  716. );
  717. }
  718. export default function Img2ImgPage() {
  719. return <Img2ImgForm />;
  720. }