page.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. "use client";
  2. import { useState, useEffect, useRef } from "react";
  3. import { Header } from "@/components/layout";
  4. import { AppLayout } from "@/components/layout";
  5. import { Button } from "@/components/ui/button";
  6. import { Input } from "@/components/ui/input";
  7. import { Textarea } from "@/components/ui/textarea";
  8. import { PromptTextarea } from "@/components/forms";
  9. import { Label } from "@/components/ui/label";
  10. import {
  11. Card,
  12. CardContent,
  13. CardHeader,
  14. CardTitle,
  15. CardDescription,
  16. } from "@/components/ui/card";
  17. import { InpaintingCanvas } from "@/components/features/image-generation";
  18. import { apiClient, type JobInfo, type JobDetailsResponse } from "@/lib/api";
  19. import { Loader2, X, Download } from "lucide-react";
  20. import { downloadAuthenticatedImage } from "@/lib/utils";
  21. import { useLocalStorage } from "@/lib/storage";
  22. import {
  23. ModelSelectionProvider,
  24. useModelSelection,
  25. useCheckpointSelection,
  26. useModelTypeSelection,
  27. } from "@/contexts/model-selection-context";
  28. import {
  29. Select,
  30. SelectContent,
  31. SelectItem,
  32. SelectTrigger,
  33. SelectValue,
  34. } from "@/components/ui/select";
  35. // import { AutoSelectionStatus } from '@/components/features/models';
  36. type InpaintingFormData = {
  37. prompt: string;
  38. negative_prompt: string;
  39. steps: number;
  40. cfg_scale: number;
  41. seed: string;
  42. sampling_method: string;
  43. strength: number;
  44. width?: number;
  45. height?: number;
  46. };
  47. const defaultFormData: InpaintingFormData = {
  48. prompt: "",
  49. negative_prompt: "",
  50. steps: 20,
  51. cfg_scale: 7.5,
  52. seed: "",
  53. sampling_method: "euler_a",
  54. strength: 0.75,
  55. width: 512,
  56. height: 512,
  57. };
  58. function InpaintingForm() {
  59. const { state, actions } = useModelSelection();
  60. const {
  61. checkpointModels,
  62. selectedCheckpointModel,
  63. selectedCheckpoint,
  64. setSelectedCheckpoint,
  65. isAutoSelecting,
  66. warnings,
  67. error: checkpointError,
  68. } = useCheckpointSelection();
  69. const {
  70. availableModels: vaeModels,
  71. selectedModel: selectedVae,
  72. isUserOverride: isVaeUserOverride,
  73. isAutoSelected: isVaeAutoSelected,
  74. setSelectedModel: setSelectedVae,
  75. setUserOverride: setVaeUserOverride,
  76. clearUserOverride: clearVaeUserOverride,
  77. } = useModelTypeSelection("vae");
  78. const [formData, setFormData] = useLocalStorage<InpaintingFormData>(
  79. "inpainting-form-data",
  80. defaultFormData,
  81. { excludeLargeData: true, maxSize: 512 * 1024 },
  82. );
  83. // Separate state for image data (not stored in localStorage)
  84. const [sourceImage, setSourceImage] = useState<string>("");
  85. const [maskImage, setMaskImage] = useState<string>("");
  86. const [loading, setLoading] = useState(false);
  87. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  88. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  89. const [loraModels, setLoraModels] = useState<string[]>([]);
  90. const [embeddings, setEmbeddings] = useState<string[]>([]);
  91. const [error, setError] = useState<string | null>(null);
  92. const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null);
  93. // Cleanup polling on unmount
  94. useEffect(() => {
  95. return () => {
  96. if (pollCleanup) {
  97. pollCleanup();
  98. }
  99. };
  100. }, [pollCleanup]);
  101. useEffect(() => {
  102. const loadModels = async () => {
  103. try {
  104. const [modelsData, loras, embeds] = await Promise.all([
  105. apiClient.getModels(), // Get all models with enhanced info
  106. apiClient.getModels("lora"),
  107. apiClient.getModels("embedding"),
  108. ]);
  109. actions.setModels(modelsData.models);
  110. setLoraModels(loras.models.map((m) => m.name));
  111. setEmbeddings(embeds.models.map((m) => m.name));
  112. } catch (err) {
  113. console.error("Failed to load models:", err);
  114. }
  115. };
  116. loadModels();
  117. }, [actions]);
  118. // Update form data when checkpoint changes
  119. useEffect(() => {
  120. if (selectedCheckpoint) {
  121. setFormData((prev) => ({
  122. ...prev,
  123. model: selectedCheckpoint,
  124. }));
  125. }
  126. }, [selectedCheckpoint, setFormData]);
  127. const handleInputChange = (
  128. e: React.ChangeEvent<
  129. HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement
  130. >,
  131. ) => {
  132. const { name, value } = e.target;
  133. setFormData((prev) => ({
  134. ...prev,
  135. [name]:
  136. name === "prompt" ||
  137. name === "negative_prompt" ||
  138. name === "seed" ||
  139. name === "sampling_method"
  140. ? value
  141. : Number(value),
  142. }));
  143. };
  144. const handleSourceImageChange = (image: string) => {
  145. setSourceImage(image);
  146. setError(null);
  147. };
  148. const handleMaskImageChange = (image: string) => {
  149. setMaskImage(image);
  150. setError(null);
  151. };
  152. const pollJobStatus = async (jobId: string) => {
  153. const maxAttempts = 300; // 5 minutes with 2 second interval
  154. let attempts = 0;
  155. let isPolling = true;
  156. let timeoutId: NodeJS.Timeout | null = null;
  157. const poll = async () => {
  158. if (!isPolling) return;
  159. try {
  160. const status: JobDetailsResponse = await apiClient.getJobStatus(jobId);
  161. setJobInfo(status.job);
  162. if (status.job.status === "completed") {
  163. let imageUrls: string[] = [];
  164. // Handle both old format (result.images) and new format (outputs)
  165. if (status.job.outputs && status.job.outputs.length > 0) {
  166. // New format: convert output URLs to authenticated image URLs with cache-busting
  167. imageUrls = status.job.outputs.map((output: any) => {
  168. const filename = output.filename;
  169. return apiClient.getImageUrl(jobId, filename);
  170. });
  171. } else if (
  172. status.job.result?.images &&
  173. status.job.result.images.length > 0
  174. ) {
  175. // Old format: convert image URLs to authenticated URLs
  176. imageUrls = status.job.result.images.map((imageUrl: string) => {
  177. // Extract filename from URL if it's already a full URL
  178. if (imageUrl.includes("/output/")) {
  179. const parts = imageUrl.split("/output/");
  180. if (parts.length === 2) {
  181. const filename = parts[1].split("?")[0]; // Remove query params
  182. return apiClient.getImageUrl(jobId, filename);
  183. }
  184. }
  185. return imageUrl; // Already a full URL
  186. });
  187. }
  188. // Create a new array to trigger React re-render
  189. setGeneratedImages([...imageUrls]);
  190. setLoading(false);
  191. isPolling = false;
  192. } else if (status.job.status === "failed") {
  193. setError(status.job.error || "Generation failed");
  194. setLoading(false);
  195. isPolling = false;
  196. } else if (status.job.status === "cancelled") {
  197. setError("Generation was cancelled");
  198. setLoading(false);
  199. isPolling = false;
  200. } else if (attempts < maxAttempts) {
  201. attempts++;
  202. timeoutId = setTimeout(poll, 2000);
  203. } else {
  204. setError("Job polling timeout");
  205. setLoading(false);
  206. isPolling = false;
  207. }
  208. } catch (err) {
  209. if (isPolling) {
  210. setError(
  211. err instanceof Error ? err.message : "Failed to check job status",
  212. );
  213. setLoading(false);
  214. isPolling = false;
  215. }
  216. }
  217. };
  218. poll();
  219. // Return cleanup function
  220. return () => {
  221. isPolling = false;
  222. if (timeoutId) {
  223. clearTimeout(timeoutId);
  224. }
  225. };
  226. };
  227. const handleGenerate = async (e: React.FormEvent) => {
  228. e.preventDefault();
  229. if (!sourceImage) {
  230. setError("Please upload a source image first");
  231. return;
  232. }
  233. if (!maskImage) {
  234. setError("Please create a mask first");
  235. return;
  236. }
  237. setLoading(true);
  238. setError(null);
  239. setGeneratedImages([]);
  240. setJobInfo(null);
  241. try {
  242. // Validate model selection
  243. if (selectedCheckpointModel) {
  244. const validation = actions.validateSelection(selectedCheckpointModel);
  245. if (!validation.isValid) {
  246. setError(
  247. `Missing required models: ${validation.missingRequired.join(", ")}`,
  248. );
  249. setLoading(false);
  250. return;
  251. }
  252. }
  253. const requestData = {
  254. ...formData,
  255. source_image: sourceImage,
  256. mask_image: maskImage,
  257. model: selectedCheckpoint || undefined,
  258. vae: selectedVae || undefined,
  259. };
  260. const job = await apiClient.inpainting(requestData);
  261. setJobInfo(job);
  262. const jobId = job.request_id || job.id;
  263. if (jobId) {
  264. const cleanup = pollJobStatus(jobId);
  265. setPollCleanup(() => cleanup);
  266. } else {
  267. setError("No job ID returned from server");
  268. setLoading(false);
  269. }
  270. } catch (err) {
  271. setError(err instanceof Error ? err.message : "Failed to generate image");
  272. setLoading(false);
  273. }
  274. };
  275. const handleCancel = async () => {
  276. const jobId = jobInfo?.request_id || jobInfo?.id;
  277. if (jobId) {
  278. try {
  279. await apiClient.cancelJob(jobId);
  280. setLoading(false);
  281. setError("Generation cancelled");
  282. // Cleanup polling
  283. if (pollCleanup) {
  284. pollCleanup();
  285. setPollCleanup(null);
  286. }
  287. } catch (err) {
  288. console.error("Failed to cancel job:", err);
  289. }
  290. }
  291. };
  292. return (
  293. <AppLayout>
  294. <Header
  295. title="Inpainting"
  296. description="Edit images by masking areas and regenerating with AI"
  297. />
  298. <div className="container mx-auto p-6">
  299. <div className="grid gap-6 lg:grid-cols-2">
  300. {/* Left Panel - Canvas and Form */}
  301. <div className="space-y-6">
  302. <InpaintingCanvas
  303. onSourceImageChange={handleSourceImageChange}
  304. onMaskImageChange={handleMaskImageChange}
  305. targetWidth={formData.width}
  306. targetHeight={formData.height}
  307. />
  308. <Card>
  309. <CardContent className="pt-6">
  310. <form onSubmit={handleGenerate} className="space-y-4">
  311. <div className="space-y-2">
  312. <Label htmlFor="prompt">Prompt *</Label>
  313. <PromptTextarea
  314. value={formData.prompt}
  315. onChange={(value) =>
  316. setFormData({ ...formData, prompt: value })
  317. }
  318. placeholder="Describe what to generate in the masked areas..."
  319. rows={3}
  320. loras={loraModels}
  321. embeddings={embeddings}
  322. />
  323. <p className="text-xs text-muted-foreground">
  324. Tip: Use {"<lora:name:weight>"} for LoRAs and embedding
  325. names directly
  326. </p>
  327. </div>
  328. <div className="space-y-2">
  329. <Label htmlFor="negative_prompt">Negative Prompt</Label>
  330. <PromptTextarea
  331. value={formData.negative_prompt || ""}
  332. onChange={(value) =>
  333. setFormData({ ...formData, negative_prompt: value })
  334. }
  335. placeholder="What to avoid in the generated areas..."
  336. rows={2}
  337. loras={loraModels}
  338. embeddings={embeddings}
  339. />
  340. </div>
  341. <div className="space-y-2">
  342. <Label htmlFor="strength">
  343. Strength: {formData.strength.toFixed(2)}
  344. </Label>
  345. <Input
  346. id="strength"
  347. name="strength"
  348. type="range"
  349. value={formData.strength}
  350. onChange={handleInputChange}
  351. min={0}
  352. max={1}
  353. step={0.05}
  354. />
  355. <p className="text-xs text-muted-foreground">
  356. Lower values preserve more of the original image
  357. </p>
  358. </div>
  359. <div className="grid grid-cols-2 gap-4">
  360. <div className="space-y-2">
  361. <Label htmlFor="width">Width</Label>
  362. <Input
  363. id="width"
  364. name="width"
  365. type="number"
  366. value={formData.width}
  367. onChange={handleInputChange}
  368. step={64}
  369. min={256}
  370. max={2048}
  371. />
  372. </div>
  373. <div className="space-y-2">
  374. <Label htmlFor="height">Height</Label>
  375. <Input
  376. id="height"
  377. name="height"
  378. type="number"
  379. value={formData.height}
  380. onChange={handleInputChange}
  381. step={64}
  382. min={256}
  383. max={2048}
  384. />
  385. </div>
  386. </div>
  387. <div className="grid grid-cols-2 gap-4">
  388. <div className="space-y-2">
  389. <Label htmlFor="steps">Steps</Label>
  390. <Input
  391. id="steps"
  392. name="steps"
  393. type="number"
  394. value={formData.steps}
  395. onChange={handleInputChange}
  396. min={1}
  397. max={150}
  398. />
  399. </div>
  400. <div className="space-y-2">
  401. <Label htmlFor="cfg_scale">CFG Scale</Label>
  402. <Input
  403. id="cfg_scale"
  404. name="cfg_scale"
  405. type="number"
  406. value={formData.cfg_scale}
  407. onChange={handleInputChange}
  408. step={0.5}
  409. min={1}
  410. max={30}
  411. />
  412. </div>
  413. </div>
  414. <div className="space-y-2">
  415. <Label htmlFor="seed">Seed (optional)</Label>
  416. <Input
  417. id="seed"
  418. name="seed"
  419. value={formData.seed}
  420. onChange={handleInputChange}
  421. placeholder="Leave empty for random"
  422. />
  423. </div>
  424. <div className="space-y-2">
  425. <Label htmlFor="sampling_method">Sampling Method</Label>
  426. <select
  427. id="sampling_method"
  428. name="sampling_method"
  429. value={formData.sampling_method}
  430. onChange={handleInputChange}
  431. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  432. >
  433. <option value="euler">Euler</option>
  434. <option value="euler_a">Euler A</option>
  435. <option value="heun">Heun</option>
  436. <option value="dpm2">DPM2</option>
  437. <option value="dpm++2s_a">DPM++ 2S A</option>
  438. <option value="dpm++2m">DPM++ 2M</option>
  439. <option value="dpm++2mv2">DPM++ 2M V2</option>
  440. <option value="lcm">LCM</option>
  441. </select>
  442. </div>
  443. {/* Model Selection Section */}
  444. <Card>
  445. <CardHeader>
  446. <CardTitle>Model Selection</CardTitle>
  447. <CardDescription>
  448. Select checkpoint and additional models for generation
  449. </CardDescription>
  450. </CardHeader>
  451. {/* Checkpoint Selection */}
  452. <div className="space-y-2">
  453. <Label htmlFor="checkpoint">Checkpoint Model *</Label>
  454. <select
  455. id="checkpoint"
  456. value={selectedCheckpoint || ""}
  457. onChange={(e) =>
  458. setSelectedCheckpoint(e.target.value || null)
  459. }
  460. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  461. disabled={isAutoSelecting}
  462. >
  463. <option value="">Select a checkpoint model...</option>
  464. {checkpointModels.map((model) => (
  465. <option key={model.id} value={model.name}>
  466. {model.name} {model.loaded ? "(Loaded)" : ""}
  467. </option>
  468. ))}
  469. </select>
  470. </div>
  471. {/* VAE Selection */}
  472. <div className="space-y-2">
  473. <Label>VAE Model (Optional)</Label>
  474. <Select
  475. value={selectedVae || ""}
  476. onValueChange={(value) => {
  477. if (value) {
  478. setSelectedVae(value);
  479. setVaeUserOverride(value);
  480. } else {
  481. clearVaeUserOverride();
  482. }
  483. }}
  484. disabled={isAutoSelecting}
  485. >
  486. <SelectTrigger>
  487. <SelectValue placeholder="Use default VAE" />
  488. </SelectTrigger>
  489. <SelectContent>
  490. <SelectItem value="">Use default VAE</SelectItem>
  491. {vaeModels.map((model) => (
  492. <SelectItem key={model.name} value={model.name}>
  493. {model.name}
  494. </SelectItem>
  495. ))}
  496. </SelectContent>
  497. </Select>
  498. {isVaeAutoSelected && (
  499. <p className="text-xs text-muted-foreground">
  500. Auto-selected VAE model
  501. </p>
  502. )}
  503. </div>
  504. </Card>
  505. <div className="flex gap-2">
  506. <Button
  507. type="submit"
  508. disabled={loading || !sourceImage || !maskImage}
  509. className="flex-1"
  510. >
  511. {loading ? (
  512. <>
  513. <Loader2 className="h-4 w-4 animate-spin" />
  514. Generating...
  515. </>
  516. ) : (
  517. "Generate"
  518. )}
  519. </Button>
  520. {loading && (
  521. <Button
  522. type="button"
  523. variant="destructive"
  524. onClick={handleCancel}
  525. >
  526. <X className="h-4 w-4" />
  527. Cancel
  528. </Button>
  529. )}
  530. </div>
  531. {error && (
  532. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  533. {error}
  534. </div>
  535. )}
  536. </form>
  537. </CardContent>
  538. </Card>
  539. </div>
  540. {/* Right Panel - Generated Images */}
  541. <Card>
  542. <CardContent className="pt-6">
  543. <div className="space-y-4">
  544. <h3 className="text-lg font-semibold">Generated Images</h3>
  545. {generatedImages.length === 0 ? (
  546. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  547. <p className="text-muted-foreground">
  548. {loading
  549. ? "Generating..."
  550. : "Generated images will appear here"}
  551. </p>
  552. </div>
  553. ) : (
  554. <div className="grid gap-4">
  555. {generatedImages.map((image, index) => (
  556. <div key={index} className="relative group">
  557. <img
  558. src={image}
  559. alt={`Generated ${index + 1}`}
  560. className="w-full rounded-lg border border-border"
  561. />
  562. <Button
  563. size="icon"
  564. variant="secondary"
  565. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  566. onClick={() => {
  567. const authToken =
  568. localStorage.getItem("auth_token");
  569. const unixUser = localStorage.getItem("unix_user");
  570. downloadAuthenticatedImage(
  571. image,
  572. `inpainting-${Date.now()}-${index}.png`,
  573. authToken || undefined,
  574. unixUser || undefined,
  575. ).catch((err) => {
  576. console.error("Failed to download image:", err);
  577. });
  578. }}
  579. >
  580. <Download className="h-4 w-4" />
  581. </Button>
  582. </div>
  583. ))}
  584. </div>
  585. )}
  586. </div>
  587. </CardContent>
  588. </Card>
  589. </div>
  590. </div>
  591. </AppLayout>
  592. );
  593. }
  594. export default function InpaintingPage() {
  595. return <InpaintingForm />;
  596. }