page.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. 'use client';
  2. import { useState, useEffect } from 'react';
  3. import { Header } from '@/components/header';
  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/prompt-textarea';
  9. import { Label } from '@/components/ui/label';
  10. import { Card, CardContent } from '@/components/ui/card';
  11. import { apiClient, type GenerationRequest, type JobInfo, type ModelInfo } from '@/lib/api';
  12. import { Loader2, Download, X, Trash2, RotateCcw, Power } from 'lucide-react';
  13. import { downloadImage } from '@/lib/utils';
  14. import { useLocalStorage } from '@/lib/hooks';
  15. const defaultFormData: GenerationRequest = {
  16. prompt: '',
  17. negative_prompt: '',
  18. width: 512,
  19. height: 512,
  20. steps: 20,
  21. cfg_scale: 7.5,
  22. seed: '',
  23. sampling_method: 'euler_a',
  24. scheduler: 'default',
  25. batch_count: 1,
  26. };
  27. export default function Text2ImgPage() {
  28. const [formData, setFormData] = useLocalStorage<GenerationRequest>(
  29. 'text2img-form-data',
  30. defaultFormData
  31. );
  32. const [loading, setLoading] = useState(false);
  33. const [error, setError] = useState<string | null>(null);
  34. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  35. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  36. const [samplers, setSamplers] = useState<Array<{ name: string; description: string }>>([]);
  37. const [schedulers, setSchedulers] = useState<Array<{ name: string; description: string }>>([]);
  38. const [vaeModels, setVaeModels] = useState<ModelInfo[]>([]);
  39. const [selectedVae, setSelectedVae] = useState<string>('');
  40. const [loraModels, setLoraModels] = useState<string[]>([]);
  41. const [embeddings, setEmbeddings] = useState<string[]>([]);
  42. useEffect(() => {
  43. const loadOptions = async () => {
  44. try {
  45. const [samplersData, schedulersData, models, loras, embeds] = await Promise.all([
  46. apiClient.getSamplers(),
  47. apiClient.getSchedulers(),
  48. apiClient.getModels('vae'),
  49. apiClient.getModels('lora'),
  50. apiClient.getModels('embedding'),
  51. ]);
  52. setSamplers(samplersData);
  53. setSchedulers(schedulersData);
  54. setVaeModels(models);
  55. setLoraModels(loras.map(m => m.name));
  56. setEmbeddings(embeds.map(m => m.name));
  57. } catch (err) {
  58. console.error('Failed to load options:', err);
  59. }
  60. };
  61. loadOptions();
  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' || name === 'scheduler'
  70. ? value
  71. : Number(value),
  72. }));
  73. };
  74. const pollJobStatus = async (jobId: string) => {
  75. const maxAttempts = 300; // 5 minutes with 1 second interval
  76. let attempts = 0;
  77. const poll = async () => {
  78. try {
  79. const status = await apiClient.getJobStatus(jobId);
  80. setJobInfo(status);
  81. if (status.status === 'completed' && status.result?.images) {
  82. setGeneratedImages(status.result.images);
  83. setLoading(false);
  84. } else if (status.status === 'failed') {
  85. setError(status.error || 'Generation failed');
  86. setLoading(false);
  87. } else if (status.status === 'cancelled') {
  88. setError('Generation was cancelled');
  89. setLoading(false);
  90. } else if (attempts < maxAttempts) {
  91. attempts++;
  92. setTimeout(poll, 1000);
  93. } else {
  94. setError('Job polling timeout');
  95. setLoading(false);
  96. }
  97. } catch (err) {
  98. setError(err instanceof Error ? err.message : 'Failed to check job status');
  99. setLoading(false);
  100. }
  101. };
  102. poll();
  103. };
  104. const handleGenerate = async (e: React.FormEvent) => {
  105. e.preventDefault();
  106. setLoading(true);
  107. setError(null);
  108. setGeneratedImages([]);
  109. setJobInfo(null);
  110. try {
  111. const job = await apiClient.text2img(formData);
  112. setJobInfo(job);
  113. const jobId = job.request_id || job.id;
  114. if (jobId) {
  115. await pollJobStatus(jobId);
  116. } else {
  117. setError('No job ID returned from server');
  118. setLoading(false);
  119. }
  120. } catch (err) {
  121. setError(err instanceof Error ? err.message : 'Failed to generate image');
  122. setLoading(false);
  123. }
  124. };
  125. const handleCancel = async () => {
  126. const jobId = jobInfo?.request_id || jobInfo?.id;
  127. if (jobId) {
  128. try {
  129. await apiClient.cancelJob(jobId);
  130. setLoading(false);
  131. setError('Generation cancelled');
  132. } catch (err) {
  133. console.error('Failed to cancel job:', err);
  134. }
  135. }
  136. };
  137. const handleClearPrompts = () => {
  138. setFormData({ ...formData, prompt: '', negative_prompt: '' });
  139. };
  140. const handleResetToDefaults = () => {
  141. setFormData(defaultFormData);
  142. setSelectedVae('');
  143. };
  144. const handleServerRestart = async () => {
  145. if (!confirm('Are you sure you want to restart the server? This will cancel all running jobs.')) {
  146. return;
  147. }
  148. try {
  149. setLoading(true);
  150. await apiClient.restartServer();
  151. setError('Server restart initiated. Please wait...');
  152. setTimeout(() => {
  153. window.location.reload();
  154. }, 3000);
  155. } catch (err) {
  156. setError(err instanceof Error ? err.message : 'Failed to restart server');
  157. setLoading(false);
  158. }
  159. };
  160. return (
  161. <AppLayout>
  162. <Header title="Text to Image" description="Generate images from text prompts" />
  163. <div className="container mx-auto p-6">
  164. <div className="grid gap-6 lg:grid-cols-2">
  165. {/* Left Panel - Form */}
  166. <Card>
  167. <CardContent className="pt-6">
  168. <form onSubmit={handleGenerate} className="space-y-4">
  169. <div className="space-y-2">
  170. <Label htmlFor="prompt">Prompt *</Label>
  171. <PromptTextarea
  172. value={formData.prompt}
  173. onChange={(value) => setFormData({ ...formData, prompt: value })}
  174. placeholder="a beautiful landscape with mountains and a lake, sunset, highly detailed..."
  175. rows={4}
  176. loras={loraModels}
  177. embeddings={embeddings}
  178. />
  179. <p className="text-xs text-muted-foreground">
  180. Tip: Use &lt;lora:name:weight&gt; for LoRAs (e.g., &lt;lora:myLora:0.8&gt;) and embedding names directly
  181. </p>
  182. </div>
  183. <div className="space-y-2">
  184. <Label htmlFor="negative_prompt">Negative Prompt</Label>
  185. <PromptTextarea
  186. value={formData.negative_prompt || ''}
  187. onChange={(value) => setFormData({ ...formData, negative_prompt: value })}
  188. placeholder="blurry, low quality, distorted..."
  189. rows={2}
  190. loras={loraModels}
  191. embeddings={embeddings}
  192. />
  193. </div>
  194. {/* Utility Buttons */}
  195. <div className="flex gap-2">
  196. <Button
  197. type="button"
  198. variant="outline"
  199. size="sm"
  200. onClick={handleClearPrompts}
  201. disabled={loading}
  202. title="Clear both prompts"
  203. >
  204. <Trash2 className="h-4 w-4 mr-1" />
  205. Clear Prompts
  206. </Button>
  207. <Button
  208. type="button"
  209. variant="outline"
  210. size="sm"
  211. onClick={handleResetToDefaults}
  212. disabled={loading}
  213. title="Reset all fields to defaults"
  214. >
  215. <RotateCcw className="h-4 w-4 mr-1" />
  216. Reset to Defaults
  217. </Button>
  218. <Button
  219. type="button"
  220. variant="outline"
  221. size="sm"
  222. onClick={handleServerRestart}
  223. disabled={loading}
  224. title="Restart the backend server"
  225. >
  226. <Power className="h-4 w-4 mr-1" />
  227. Restart Server
  228. </Button>
  229. </div>
  230. <div className="grid grid-cols-2 gap-4">
  231. <div className="space-y-2">
  232. <Label htmlFor="width">Width</Label>
  233. <Input
  234. id="width"
  235. name="width"
  236. type="number"
  237. value={formData.width}
  238. onChange={handleInputChange}
  239. step={64}
  240. min={256}
  241. max={2048}
  242. />
  243. </div>
  244. <div className="space-y-2">
  245. <Label htmlFor="height">Height</Label>
  246. <Input
  247. id="height"
  248. name="height"
  249. type="number"
  250. value={formData.height}
  251. onChange={handleInputChange}
  252. step={64}
  253. min={256}
  254. max={2048}
  255. />
  256. </div>
  257. </div>
  258. <div className="grid grid-cols-2 gap-4">
  259. <div className="space-y-2">
  260. <Label htmlFor="steps">Steps</Label>
  261. <Input
  262. id="steps"
  263. name="steps"
  264. type="number"
  265. value={formData.steps}
  266. onChange={handleInputChange}
  267. min={1}
  268. max={150}
  269. />
  270. </div>
  271. <div className="space-y-2">
  272. <Label htmlFor="cfg_scale">CFG Scale</Label>
  273. <Input
  274. id="cfg_scale"
  275. name="cfg_scale"
  276. type="number"
  277. value={formData.cfg_scale}
  278. onChange={handleInputChange}
  279. step={0.5}
  280. min={1}
  281. max={30}
  282. />
  283. </div>
  284. </div>
  285. <div className="space-y-2">
  286. <Label htmlFor="seed">Seed (optional)</Label>
  287. <Input
  288. id="seed"
  289. name="seed"
  290. value={formData.seed}
  291. onChange={handleInputChange}
  292. placeholder="Leave empty for random"
  293. />
  294. </div>
  295. <div className="space-y-2">
  296. <Label htmlFor="sampling_method">Sampling Method</Label>
  297. <select
  298. id="sampling_method"
  299. name="sampling_method"
  300. value={formData.sampling_method}
  301. onChange={handleInputChange}
  302. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  303. >
  304. {samplers.length > 0 ? (
  305. samplers.map((sampler) => (
  306. <option key={sampler.name} value={sampler.name}>
  307. {sampler.name.toUpperCase()} - {sampler.description}
  308. </option>
  309. ))
  310. ) : (
  311. <option value="euler_a">Loading...</option>
  312. )}
  313. </select>
  314. </div>
  315. <div className="space-y-2">
  316. <Label htmlFor="scheduler">Scheduler</Label>
  317. <select
  318. id="scheduler"
  319. name="scheduler"
  320. value={formData.scheduler}
  321. onChange={handleInputChange}
  322. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  323. >
  324. {schedulers.length > 0 ? (
  325. schedulers.map((scheduler) => (
  326. <option key={scheduler.name} value={scheduler.name}>
  327. {scheduler.name.toUpperCase()} - {scheduler.description}
  328. </option>
  329. ))
  330. ) : (
  331. <option value="default">Loading...</option>
  332. )}
  333. </select>
  334. </div>
  335. <div className="space-y-2">
  336. <Label htmlFor="vae">VAE (optional)</Label>
  337. <select
  338. id="vae"
  339. value={selectedVae}
  340. onChange={(e) => setSelectedVae(e.target.value)}
  341. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  342. >
  343. <option value="">Default VAE</option>
  344. {vaeModels.map((vae) => (
  345. <option key={vae.id} value={vae.name}>
  346. {vae.name}
  347. </option>
  348. ))}
  349. </select>
  350. </div>
  351. <div className="space-y-2">
  352. <Label htmlFor="batch_count">Batch Count</Label>
  353. <Input
  354. id="batch_count"
  355. name="batch_count"
  356. type="number"
  357. value={formData.batch_count}
  358. onChange={handleInputChange}
  359. min={1}
  360. max={4}
  361. />
  362. </div>
  363. <div className="flex gap-2">
  364. <Button type="submit" disabled={loading} className="flex-1">
  365. {loading ? (
  366. <>
  367. <Loader2 className="h-4 w-4 animate-spin" />
  368. Generating...
  369. </>
  370. ) : (
  371. 'Generate'
  372. )}
  373. </Button>
  374. {loading && (
  375. <Button type="button" variant="destructive" onClick={handleCancel}>
  376. <X className="h-4 w-4" />
  377. Cancel
  378. </Button>
  379. )}
  380. </div>
  381. {error && (
  382. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  383. {error}
  384. </div>
  385. )}
  386. {loading && jobInfo && (
  387. <div className="rounded-md bg-muted p-3 text-sm">
  388. <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
  389. <p>Status: {jobInfo.status}</p>
  390. {jobInfo.progress !== undefined && (
  391. <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
  392. )}
  393. </div>
  394. )}
  395. </form>
  396. </CardContent>
  397. </Card>
  398. {/* Right Panel - Generated Images */}
  399. <Card>
  400. <CardContent className="pt-6">
  401. <div className="space-y-4">
  402. <h3 className="text-lg font-semibold">Generated Images</h3>
  403. {generatedImages.length === 0 ? (
  404. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  405. <p className="text-muted-foreground">
  406. {loading ? 'Generating...' : 'Generated images will appear here'}
  407. </p>
  408. </div>
  409. ) : (
  410. <div className="grid gap-4">
  411. {generatedImages.map((image, index) => (
  412. <div key={index} className="relative group">
  413. <img
  414. src={image}
  415. alt={`Generated ${index + 1}`}
  416. className="w-full rounded-lg border border-border"
  417. />
  418. <Button
  419. size="icon"
  420. variant="secondary"
  421. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  422. onClick={() => downloadImage(image, `generated-${Date.now()}-${index}.png`)}
  423. >
  424. <Download className="h-4 w-4" />
  425. </Button>
  426. </div>
  427. ))}
  428. </div>
  429. )}
  430. </div>
  431. </CardContent>
  432. </Card>
  433. </div>
  434. </div>
  435. </AppLayout>
  436. );
  437. }