page.tsx 18 KB

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