page.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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, downloadAuthenticatedImage } 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') {
  82. let imageUrls: string[] = [];
  83. // Handle both old format (result.images) and new format (outputs)
  84. if (status.outputs && status.outputs.length > 0) {
  85. // New format: convert output URLs to authenticated image URLs with cache-busting
  86. imageUrls = status.outputs.map((output: any) => {
  87. const filename = output.filename;
  88. return apiClient.getImageUrl(jobId, filename);
  89. });
  90. } else if (status.result?.images && status.result.images.length > 0) {
  91. // Old format: convert image URLs to authenticated URLs
  92. imageUrls = status.result.images.map((imageUrl: string) => {
  93. // Extract filename from URL if it's already a full URL
  94. if (imageUrl.includes('/output/')) {
  95. const parts = imageUrl.split('/output/');
  96. if (parts.length === 2) {
  97. const filename = parts[1].split('?')[0]; // Remove query params
  98. return apiClient.getImageUrl(jobId, filename);
  99. }
  100. }
  101. // If it's just a filename, convert it directly
  102. return apiClient.getImageUrl(jobId, imageUrl);
  103. });
  104. }
  105. // Create a new array to trigger React re-render
  106. setGeneratedImages([...imageUrls]);
  107. setLoading(false);
  108. } else if (status.status === 'failed') {
  109. setError(status.error || 'Generation failed');
  110. setLoading(false);
  111. } else if (status.status === 'cancelled') {
  112. setError('Generation was cancelled');
  113. setLoading(false);
  114. } else if (attempts < maxAttempts) {
  115. attempts++;
  116. setTimeout(poll, 1000);
  117. } else {
  118. setError('Job polling timeout');
  119. setLoading(false);
  120. }
  121. } catch (err) {
  122. setError(err instanceof Error ? err.message : 'Failed to check job status');
  123. setLoading(false);
  124. }
  125. };
  126. poll();
  127. };
  128. const handleGenerate = async (e: React.FormEvent) => {
  129. e.preventDefault();
  130. setLoading(true);
  131. setError(null);
  132. setGeneratedImages([]);
  133. setJobInfo(null);
  134. try {
  135. const job = await apiClient.text2img(formData);
  136. setJobInfo(job);
  137. const jobId = job.request_id || job.id;
  138. if (jobId) {
  139. await pollJobStatus(jobId);
  140. } else {
  141. setError('No job ID returned from server');
  142. setLoading(false);
  143. }
  144. } catch (err) {
  145. setError(err instanceof Error ? err.message : 'Failed to generate image');
  146. setLoading(false);
  147. }
  148. };
  149. const handleCancel = async () => {
  150. const jobId = jobInfo?.request_id || jobInfo?.id;
  151. if (jobId) {
  152. try {
  153. await apiClient.cancelJob(jobId);
  154. setLoading(false);
  155. setError('Generation cancelled');
  156. } catch (err) {
  157. console.error('Failed to cancel job:', err);
  158. }
  159. }
  160. };
  161. const handleClearPrompts = () => {
  162. setFormData({ ...formData, prompt: '', negative_prompt: '' });
  163. };
  164. const handleResetToDefaults = () => {
  165. setFormData(defaultFormData);
  166. setSelectedVae('');
  167. };
  168. const handleServerRestart = async () => {
  169. if (!confirm('Are you sure you want to restart the server? This will cancel all running jobs.')) {
  170. return;
  171. }
  172. try {
  173. setLoading(true);
  174. await apiClient.restartServer();
  175. setError('Server restart initiated. Please wait...');
  176. setTimeout(() => {
  177. window.location.reload();
  178. }, 3000);
  179. } catch (err) {
  180. setError(err instanceof Error ? err.message : 'Failed to restart server');
  181. setLoading(false);
  182. }
  183. };
  184. return (
  185. <AppLayout>
  186. <Header title="Text to Image" description="Generate images from text prompts" />
  187. <div className="container mx-auto p-6">
  188. <div className="grid gap-6 lg:grid-cols-2">
  189. {/* Left Panel - Form */}
  190. <Card>
  191. <CardContent className="pt-6">
  192. <form onSubmit={handleGenerate} className="space-y-4">
  193. <div className="space-y-2">
  194. <Label htmlFor="prompt">Prompt *</Label>
  195. <PromptTextarea
  196. value={formData.prompt}
  197. onChange={(value) => setFormData({ ...formData, prompt: value })}
  198. placeholder="a beautiful landscape with mountains and a lake, sunset, highly detailed..."
  199. rows={4}
  200. loras={loraModels}
  201. embeddings={embeddings}
  202. />
  203. <p className="text-xs text-muted-foreground">
  204. Tip: Use &lt;lora:name:weight&gt; for LoRAs (e.g., &lt;lora:myLora:0.8&gt;) and embedding names directly
  205. </p>
  206. </div>
  207. <div className="space-y-2">
  208. <Label htmlFor="negative_prompt">Negative Prompt</Label>
  209. <PromptTextarea
  210. value={formData.negative_prompt || ''}
  211. onChange={(value) => setFormData({ ...formData, negative_prompt: value })}
  212. placeholder="blurry, low quality, distorted..."
  213. rows={2}
  214. loras={loraModels}
  215. embeddings={embeddings}
  216. />
  217. </div>
  218. {/* Utility Buttons */}
  219. <div className="flex gap-2">
  220. <Button
  221. type="button"
  222. variant="outline"
  223. size="sm"
  224. onClick={handleClearPrompts}
  225. disabled={loading}
  226. title="Clear both prompts"
  227. >
  228. <Trash2 className="h-4 w-4 mr-1" />
  229. Clear Prompts
  230. </Button>
  231. <Button
  232. type="button"
  233. variant="outline"
  234. size="sm"
  235. onClick={handleResetToDefaults}
  236. disabled={loading}
  237. title="Reset all fields to defaults"
  238. >
  239. <RotateCcw className="h-4 w-4 mr-1" />
  240. Reset to Defaults
  241. </Button>
  242. <Button
  243. type="button"
  244. variant="outline"
  245. size="sm"
  246. onClick={handleServerRestart}
  247. disabled={loading}
  248. title="Restart the backend server"
  249. >
  250. <Power className="h-4 w-4 mr-1" />
  251. Restart Server
  252. </Button>
  253. </div>
  254. <div className="grid grid-cols-2 gap-4">
  255. <div className="space-y-2">
  256. <Label htmlFor="width">Width</Label>
  257. <Input
  258. id="width"
  259. name="width"
  260. type="number"
  261. value={formData.width}
  262. onChange={handleInputChange}
  263. step={64}
  264. min={256}
  265. max={2048}
  266. />
  267. </div>
  268. <div className="space-y-2">
  269. <Label htmlFor="height">Height</Label>
  270. <Input
  271. id="height"
  272. name="height"
  273. type="number"
  274. value={formData.height}
  275. onChange={handleInputChange}
  276. step={64}
  277. min={256}
  278. max={2048}
  279. />
  280. </div>
  281. </div>
  282. <div className="grid grid-cols-2 gap-4">
  283. <div className="space-y-2">
  284. <Label htmlFor="steps">Steps</Label>
  285. <Input
  286. id="steps"
  287. name="steps"
  288. type="number"
  289. value={formData.steps}
  290. onChange={handleInputChange}
  291. min={1}
  292. max={150}
  293. />
  294. </div>
  295. <div className="space-y-2">
  296. <Label htmlFor="cfg_scale">CFG Scale</Label>
  297. <Input
  298. id="cfg_scale"
  299. name="cfg_scale"
  300. type="number"
  301. value={formData.cfg_scale}
  302. onChange={handleInputChange}
  303. step={0.5}
  304. min={1}
  305. max={30}
  306. />
  307. </div>
  308. </div>
  309. <div className="space-y-2">
  310. <Label htmlFor="seed">Seed (optional)</Label>
  311. <Input
  312. id="seed"
  313. name="seed"
  314. value={formData.seed}
  315. onChange={handleInputChange}
  316. placeholder="Leave empty for random"
  317. />
  318. </div>
  319. <div className="space-y-2">
  320. <Label htmlFor="sampling_method">Sampling Method</Label>
  321. <select
  322. id="sampling_method"
  323. name="sampling_method"
  324. value={formData.sampling_method}
  325. onChange={handleInputChange}
  326. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  327. >
  328. {samplers.length > 0 ? (
  329. samplers.map((sampler) => (
  330. <option key={sampler.name} value={sampler.name}>
  331. {sampler.name.toUpperCase()} - {sampler.description}
  332. </option>
  333. ))
  334. ) : (
  335. <option value="euler_a">Loading...</option>
  336. )}
  337. </select>
  338. </div>
  339. <div className="space-y-2">
  340. <Label htmlFor="scheduler">Scheduler</Label>
  341. <select
  342. id="scheduler"
  343. name="scheduler"
  344. value={formData.scheduler}
  345. onChange={handleInputChange}
  346. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  347. >
  348. {schedulers.length > 0 ? (
  349. schedulers.map((scheduler) => (
  350. <option key={scheduler.name} value={scheduler.name}>
  351. {scheduler.name.toUpperCase()} - {scheduler.description}
  352. </option>
  353. ))
  354. ) : (
  355. <option value="default">Loading...</option>
  356. )}
  357. </select>
  358. </div>
  359. <div className="space-y-2">
  360. <Label htmlFor="vae">VAE (optional)</Label>
  361. <select
  362. id="vae"
  363. value={selectedVae}
  364. onChange={(e) => setSelectedVae(e.target.value)}
  365. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  366. >
  367. <option value="">Default VAE</option>
  368. {vaeModels.map((vae) => (
  369. <option key={vae.id} value={vae.name}>
  370. {vae.name}
  371. </option>
  372. ))}
  373. </select>
  374. </div>
  375. <div className="space-y-2">
  376. <Label htmlFor="batch_count">Batch Count</Label>
  377. <Input
  378. id="batch_count"
  379. name="batch_count"
  380. type="number"
  381. value={formData.batch_count}
  382. onChange={handleInputChange}
  383. min={1}
  384. max={4}
  385. />
  386. </div>
  387. <div className="flex gap-2">
  388. <Button type="submit" disabled={loading} className="flex-1">
  389. {loading ? (
  390. <>
  391. <Loader2 className="h-4 w-4 animate-spin" />
  392. Generating...
  393. </>
  394. ) : (
  395. 'Generate'
  396. )}
  397. </Button>
  398. {loading && (
  399. <Button type="button" variant="destructive" onClick={handleCancel}>
  400. <X className="h-4 w-4" />
  401. Cancel
  402. </Button>
  403. )}
  404. </div>
  405. {error && (
  406. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  407. {error}
  408. </div>
  409. )}
  410. {loading && jobInfo && (
  411. <div className="rounded-md bg-muted p-3 text-sm">
  412. <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
  413. <p>Status: {jobInfo.status}</p>
  414. {jobInfo.progress !== undefined && (
  415. <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
  416. )}
  417. </div>
  418. )}
  419. </form>
  420. </CardContent>
  421. </Card>
  422. {/* Right Panel - Generated Images */}
  423. <Card>
  424. <CardContent className="pt-6">
  425. <div className="space-y-4">
  426. <h3 className="text-lg font-semibold">Generated Images</h3>
  427. {generatedImages.length === 0 ? (
  428. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  429. <p className="text-muted-foreground">
  430. {loading ? 'Generating...' : 'Generated images will appear here'}
  431. </p>
  432. </div>
  433. ) : (
  434. <div className="grid gap-4">
  435. {generatedImages.map((image, index) => (
  436. <div key={index} className="relative group">
  437. <img
  438. src={image}
  439. alt={`Generated ${index + 1}`}
  440. className="w-full rounded-lg border border-border"
  441. />
  442. <Button
  443. size="icon"
  444. variant="secondary"
  445. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  446. onClick={() => {
  447. const authToken = localStorage.getItem('auth_token');
  448. const unixUser = localStorage.getItem('unix_user');
  449. downloadAuthenticatedImage(image, `generated-${Date.now()}-${index}.png`, authToken || undefined, unixUser || undefined)
  450. .catch(err => {
  451. console.error('Failed to download image:', err);
  452. // Fallback to regular download if authenticated download fails
  453. downloadImage(image, `generated-${Date.now()}-${index}.png`);
  454. });
  455. }}
  456. >
  457. <Download className="h-4 w-4" />
  458. </Button>
  459. </div>
  460. ))}
  461. </div>
  462. )}
  463. </div>
  464. </CardContent>
  465. </Card>
  466. </div>
  467. </div>
  468. </AppLayout>
  469. );
  470. }