page.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. 'use client';
  2. import { useState, useRef, useEffect } from 'react';
  3. import { Header } from '@/components/header';
  4. import { MainLayout } from '@/components/main-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/prompt-textarea';
  9. import { Label } from '@/components/ui/label';
  10. import { Card, CardContent } from '@/components/ui/card';
  11. import { apiClient, type JobInfo } from '@/lib/api';
  12. import { Loader2, Download, X, Upload } from 'lucide-react';
  13. import { downloadImage, fileToBase64 } from '@/lib/utils';
  14. import { useLocalStorage } from '@/lib/hooks';
  15. type Img2ImgFormData = {
  16. prompt: string;
  17. negative_prompt: string;
  18. image: string;
  19. strength: number;
  20. steps: number;
  21. cfg_scale: number;
  22. seed: string;
  23. sampling_method: string;
  24. };
  25. const defaultFormData: Img2ImgFormData = {
  26. prompt: '',
  27. negative_prompt: '',
  28. image: '',
  29. strength: 0.75,
  30. steps: 20,
  31. cfg_scale: 7.5,
  32. seed: '',
  33. sampling_method: 'euler_a',
  34. };
  35. export default function Img2ImgPage() {
  36. const [formData, setFormData] = useLocalStorage<Img2ImgFormData>(
  37. 'img2img-form-data',
  38. defaultFormData
  39. );
  40. const [loading, setLoading] = useState(false);
  41. const [error, setError] = useState<string | null>(null);
  42. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  43. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  44. const [previewImage, setPreviewImage] = useState<string | null>(null);
  45. const [loraModels, setLoraModels] = useState<string[]>([]);
  46. const [embeddings, setEmbeddings] = useState<string[]>([]);
  47. const fileInputRef = useRef<HTMLInputElement>(null);
  48. useEffect(() => {
  49. const loadModels = async () => {
  50. try {
  51. const [loras, embeds] = await Promise.all([
  52. apiClient.getModels('lora'),
  53. apiClient.getModels('embedding'),
  54. ]);
  55. setLoraModels(loras.map(m => m.name));
  56. setEmbeddings(embeds.map(m => m.name));
  57. } catch (err) {
  58. console.error('Failed to load models:', err);
  59. }
  60. };
  61. loadModels();
  62. }, []);
  63. const handleInputChange = (
  64. e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  65. ) => {
  66. const { name, value } = e.target;
  67. setFormData((prev) => ({
  68. ...prev,
  69. [name]: name === 'prompt' || name === 'negative_prompt' || name === 'seed' || name === 'sampling_method'
  70. ? value
  71. : Number(value),
  72. }));
  73. };
  74. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  75. const file = e.target.files?.[0];
  76. if (!file) return;
  77. try {
  78. const base64 = await fileToBase64(file);
  79. setFormData((prev) => ({ ...prev, image: base64 }));
  80. setPreviewImage(base64);
  81. setError(null);
  82. } catch (err) {
  83. setError('Failed to load image');
  84. }
  85. };
  86. const pollJobStatus = async (jobId: string) => {
  87. const maxAttempts = 300;
  88. let attempts = 0;
  89. const poll = async () => {
  90. try {
  91. const status = await apiClient.getJobStatus(jobId);
  92. setJobInfo(status);
  93. if (status.status === 'completed' && status.result?.images) {
  94. setGeneratedImages(status.result.images);
  95. setLoading(false);
  96. } else if (status.status === 'failed') {
  97. setError(status.error || 'Generation failed');
  98. setLoading(false);
  99. } else if (status.status === 'cancelled') {
  100. setError('Generation was cancelled');
  101. setLoading(false);
  102. } else if (attempts < maxAttempts) {
  103. attempts++;
  104. setTimeout(poll, 1000);
  105. } else {
  106. setError('Job polling timeout');
  107. setLoading(false);
  108. }
  109. } catch (err) {
  110. setError(err instanceof Error ? err.message : 'Failed to check job status');
  111. setLoading(false);
  112. }
  113. };
  114. poll();
  115. };
  116. const handleGenerate = async (e: React.FormEvent) => {
  117. e.preventDefault();
  118. if (!formData.image) {
  119. setError('Please upload an image first');
  120. return;
  121. }
  122. setLoading(true);
  123. setError(null);
  124. setGeneratedImages([]);
  125. setJobInfo(null);
  126. try {
  127. const job = await apiClient.img2img(formData);
  128. setJobInfo(job);
  129. const jobId = job.request_id || job.id;
  130. if (jobId) {
  131. await pollJobStatus(jobId);
  132. } else {
  133. setError('No job ID returned from server');
  134. setLoading(false);
  135. }
  136. } catch (err) {
  137. setError(err instanceof Error ? err.message : 'Failed to generate image');
  138. setLoading(false);
  139. }
  140. };
  141. const handleCancel = async () => {
  142. const jobId = jobInfo?.request_id || jobInfo?.id;
  143. if (jobId) {
  144. try {
  145. await apiClient.cancelJob(jobId);
  146. setLoading(false);
  147. setError('Generation cancelled');
  148. } catch (err) {
  149. console.error('Failed to cancel job:', err);
  150. }
  151. }
  152. };
  153. return (
  154. <MainLayout>
  155. <Header title="Image to Image" description="Transform images with AI using text prompts" />
  156. <div className="container mx-auto p-6">
  157. <div className="grid gap-6 lg:grid-cols-2">
  158. {/* Left Panel - Form */}
  159. <Card>
  160. <CardContent className="pt-6">
  161. <form onSubmit={handleGenerate} className="space-y-4">
  162. <div className="space-y-2">
  163. <Label>Source Image *</Label>
  164. <div className="space-y-4">
  165. {previewImage && (
  166. <div className="relative">
  167. <img
  168. src={previewImage}
  169. alt="Source"
  170. className="w-full rounded-lg border border-border"
  171. />
  172. </div>
  173. )}
  174. <Button
  175. type="button"
  176. variant="outline"
  177. onClick={() => fileInputRef.current?.click()}
  178. className="w-full"
  179. >
  180. <Upload className="h-4 w-4" />
  181. {previewImage ? 'Change Image' : 'Upload Image'}
  182. </Button>
  183. <input
  184. ref={fileInputRef}
  185. type="file"
  186. accept="image/*"
  187. onChange={handleImageUpload}
  188. className="hidden"
  189. />
  190. </div>
  191. </div>
  192. <div className="space-y-2">
  193. <Label htmlFor="prompt">Prompt *</Label>
  194. <PromptTextarea
  195. value={formData.prompt}
  196. onChange={(value) => setFormData({ ...formData, prompt: value })}
  197. placeholder="Describe the transformation you want..."
  198. rows={3}
  199. loras={loraModels}
  200. embeddings={embeddings}
  201. />
  202. <p className="text-xs text-muted-foreground">
  203. Tip: Use &lt;lora:name:weight&gt; for LoRAs and embedding names directly
  204. </p>
  205. </div>
  206. <div className="space-y-2">
  207. <Label htmlFor="negative_prompt">Negative Prompt</Label>
  208. <PromptTextarea
  209. value={formData.negative_prompt || ''}
  210. onChange={(value) => setFormData({ ...formData, negative_prompt: value })}
  211. placeholder="What to avoid..."
  212. rows={2}
  213. loras={loraModels}
  214. embeddings={embeddings}
  215. />
  216. </div>
  217. <div className="space-y-2">
  218. <Label htmlFor="strength">
  219. Strength: {formData.strength.toFixed(2)}
  220. </Label>
  221. <Input
  222. id="strength"
  223. name="strength"
  224. type="range"
  225. value={formData.strength}
  226. onChange={handleInputChange}
  227. min={0}
  228. max={1}
  229. step={0.05}
  230. />
  231. <p className="text-xs text-muted-foreground">
  232. Lower values preserve more of the original image
  233. </p>
  234. </div>
  235. <div className="grid grid-cols-2 gap-4">
  236. <div className="space-y-2">
  237. <Label htmlFor="steps">Steps</Label>
  238. <Input
  239. id="steps"
  240. name="steps"
  241. type="number"
  242. value={formData.steps}
  243. onChange={handleInputChange}
  244. min={1}
  245. max={150}
  246. />
  247. </div>
  248. <div className="space-y-2">
  249. <Label htmlFor="cfg_scale">CFG Scale</Label>
  250. <Input
  251. id="cfg_scale"
  252. name="cfg_scale"
  253. type="number"
  254. value={formData.cfg_scale}
  255. onChange={handleInputChange}
  256. step={0.5}
  257. min={1}
  258. max={30}
  259. />
  260. </div>
  261. </div>
  262. <div className="space-y-2">
  263. <Label htmlFor="seed">Seed (optional)</Label>
  264. <Input
  265. id="seed"
  266. name="seed"
  267. value={formData.seed}
  268. onChange={handleInputChange}
  269. placeholder="Leave empty for random"
  270. />
  271. </div>
  272. <div className="space-y-2">
  273. <Label htmlFor="sampling_method">Sampling Method</Label>
  274. <select
  275. id="sampling_method"
  276. name="sampling_method"
  277. value={formData.sampling_method}
  278. onChange={handleInputChange}
  279. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  280. >
  281. <option value="euler">Euler</option>
  282. <option value="euler_a">Euler A</option>
  283. <option value="heun">Heun</option>
  284. <option value="dpm2">DPM2</option>
  285. <option value="dpm++2s_a">DPM++ 2S A</option>
  286. <option value="dpm++2m">DPM++ 2M</option>
  287. <option value="dpm++2mv2">DPM++ 2M V2</option>
  288. <option value="lcm">LCM</option>
  289. </select>
  290. </div>
  291. <div className="flex gap-2">
  292. <Button type="submit" disabled={loading || !formData.image} className="flex-1">
  293. {loading ? (
  294. <>
  295. <Loader2 className="h-4 w-4 animate-spin" />
  296. Generating...
  297. </>
  298. ) : (
  299. 'Generate'
  300. )}
  301. </Button>
  302. {loading && (
  303. <Button type="button" variant="destructive" onClick={handleCancel}>
  304. <X className="h-4 w-4" />
  305. Cancel
  306. </Button>
  307. )}
  308. </div>
  309. {error && (
  310. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  311. {error}
  312. </div>
  313. )}
  314. {loading && jobInfo && (
  315. <div className="rounded-md bg-muted p-3 text-sm">
  316. <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
  317. <p>Status: {jobInfo.status}</p>
  318. {jobInfo.progress !== undefined && (
  319. <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
  320. )}
  321. </div>
  322. )}
  323. </form>
  324. </CardContent>
  325. </Card>
  326. {/* Right Panel - Generated Images */}
  327. <Card>
  328. <CardContent className="pt-6">
  329. <div className="space-y-4">
  330. <h3 className="text-lg font-semibold">Generated Images</h3>
  331. {generatedImages.length === 0 ? (
  332. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  333. <p className="text-muted-foreground">
  334. {loading ? 'Generating...' : 'Generated images will appear here'}
  335. </p>
  336. </div>
  337. ) : (
  338. <div className="grid gap-4">
  339. {generatedImages.map((image, index) => (
  340. <div key={index} className="relative group">
  341. <img
  342. src={image}
  343. alt={`Generated ${index + 1}`}
  344. className="w-full rounded-lg border border-border"
  345. />
  346. <Button
  347. size="icon"
  348. variant="secondary"
  349. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  350. onClick={() => downloadImage(image, `img2img-${Date.now()}-${index}.png`)}
  351. >
  352. <Download className="h-4 w-4" />
  353. </Button>
  354. </div>
  355. ))}
  356. </div>
  357. )}
  358. </div>
  359. </CardContent>
  360. </Card>
  361. </div>
  362. </div>
  363. </MainLayout>
  364. );
  365. }