page.tsx 13 KB

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