page.tsx 18 KB

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