page.tsx 19 KB

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