page.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. 'use client';
  2. import { useState, useRef, 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 { Label } from '@/components/ui/label';
  8. import { Card, CardContent } from '@/components/ui/card';
  9. import { apiClient, type JobInfo, type ModelInfo } from '@/lib/api';
  10. import { Loader2, Download, X, Upload } from 'lucide-react';
  11. import { downloadImage, downloadAuthenticatedImage, fileToBase64 } from '@/lib/utils';
  12. import { useLocalStorage } from '@/lib/hooks';
  13. type UpscalerFormData = {
  14. image: string;
  15. upscale_factor: number;
  16. model: string;
  17. };
  18. const defaultFormData: UpscalerFormData = {
  19. image: '',
  20. upscale_factor: 2,
  21. model: '',
  22. };
  23. export default function UpscalerPage() {
  24. const [formData, setFormData] = useLocalStorage<UpscalerFormData>(
  25. 'upscaler-form-data',
  26. defaultFormData
  27. );
  28. const [loading, setLoading] = useState(false);
  29. const [error, setError] = useState<string | null>(null);
  30. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  31. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  32. const [previewImage, setPreviewImage] = useState<string | null>(null);
  33. const fileInputRef = useRef<HTMLInputElement>(null);
  34. const [upscalerModels, setUpscalerModels] = useState<ModelInfo[]>([]);
  35. useEffect(() => {
  36. const loadModels = async () => {
  37. try {
  38. // Fetch ESRGAN and upscaler models
  39. const [esrganModels, upscalerMods] = await Promise.all([
  40. apiClient.getModels('esrgan'),
  41. apiClient.getModels('upscaler'),
  42. ]);
  43. const allModels = [...esrganModels.models, ...upscalerMods.models];
  44. setUpscalerModels(allModels);
  45. // Set first model as default
  46. if (allModels.length > 0 && !formData.model) {
  47. setFormData(prev => ({ ...prev, model: allModels[0].name }));
  48. }
  49. } catch (err) {
  50. console.error('Failed to load upscaler models:', err);
  51. }
  52. };
  53. loadModels();
  54. }, []);
  55. const handleInputChange = (
  56. e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  57. ) => {
  58. const { name, value } = e.target;
  59. setFormData((prev) => ({
  60. ...prev,
  61. [name]: name === 'upscale_factor' ? Number(value) : value,
  62. }));
  63. };
  64. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  65. const file = e.target.files?.[0];
  66. if (!file) return;
  67. try {
  68. const base64 = await fileToBase64(file);
  69. setFormData((prev) => ({ ...prev, image: base64 }));
  70. setPreviewImage(base64);
  71. setError(null);
  72. } catch (err) {
  73. setError('Failed to load image');
  74. }
  75. };
  76. const pollJobStatus = async (jobId: string) => {
  77. const maxAttempts = 300;
  78. let attempts = 0;
  79. const poll = async () => {
  80. try {
  81. const status = await apiClient.getJobStatus(jobId);
  82. setJobInfo(status);
  83. if (status.status === 'completed') {
  84. let imageUrls: string[] = [];
  85. // Handle both old format (result.images) and new format (outputs)
  86. if (status.outputs && status.outputs.length > 0) {
  87. // New format: convert output URLs to authenticated image URLs with cache-busting
  88. imageUrls = status.outputs.map((output: any) => {
  89. const filename = output.filename;
  90. return apiClient.getImageUrl(jobId, filename);
  91. });
  92. } else if (status.result?.images && status.result.images.length > 0) {
  93. // Old format: convert image URLs to authenticated URLs
  94. imageUrls = status.result.images.map((imageUrl: string) => {
  95. // Extract filename from URL if it's already a full URL
  96. if (imageUrl.includes('/output/')) {
  97. const parts = imageUrl.split('/output/');
  98. if (parts.length === 2) {
  99. const filename = parts[1].split('?')[0]; // Remove query params
  100. return apiClient.getImageUrl(jobId, filename);
  101. }
  102. }
  103. // If it's just a filename, convert it directly
  104. return apiClient.getImageUrl(jobId, imageUrl);
  105. });
  106. }
  107. // Create a new array to trigger React re-render
  108. setGeneratedImages([...imageUrls]);
  109. setLoading(false);
  110. } else if (status.status === 'failed') {
  111. setError(status.error || 'Upscaling failed');
  112. setLoading(false);
  113. } else if (status.status === 'cancelled') {
  114. setError('Upscaling was cancelled');
  115. setLoading(false);
  116. } else if (attempts < maxAttempts) {
  117. attempts++;
  118. setTimeout(poll, 2000);
  119. } else {
  120. setError('Job polling timeout');
  121. setLoading(false);
  122. }
  123. } catch (err) {
  124. setError(err instanceof Error ? err.message : 'Failed to check job status');
  125. setLoading(false);
  126. }
  127. };
  128. poll();
  129. };
  130. const handleUpscale = async (e: React.FormEvent) => {
  131. e.preventDefault();
  132. if (!formData.image) {
  133. setError('Please upload an image first');
  134. return;
  135. }
  136. setLoading(true);
  137. setError(null);
  138. setGeneratedImages([]);
  139. setJobInfo(null);
  140. try {
  141. // Note: You may need to adjust the API endpoint based on your backend implementation
  142. const job = await apiClient.generateImage({
  143. prompt: `upscale ${formData.upscale_factor}x`,
  144. // Add upscale-specific parameters here based on your API
  145. } as any);
  146. setJobInfo(job);
  147. const jobId = job.request_id || job.id;
  148. if (jobId) {
  149. await pollJobStatus(jobId);
  150. } else {
  151. setError('No job ID returned from server');
  152. setLoading(false);
  153. }
  154. } catch (err) {
  155. setError(err instanceof Error ? err.message : 'Failed to upscale image');
  156. setLoading(false);
  157. }
  158. };
  159. const handleCancel = async () => {
  160. const jobId = jobInfo?.request_id || jobInfo?.id;
  161. if (jobId) {
  162. try {
  163. await apiClient.cancelJob(jobId);
  164. setLoading(false);
  165. setError('Upscaling cancelled');
  166. } catch (err) {
  167. console.error('Failed to cancel job:', err);
  168. }
  169. }
  170. };
  171. return (
  172. <AppLayout>
  173. <Header title="Upscaler" description="Enhance and upscale your images with AI" />
  174. <div className="container mx-auto p-6">
  175. <div className="grid gap-6 lg:grid-cols-2">
  176. {/* Left Panel - Form */}
  177. <Card>
  178. <CardContent className="pt-6">
  179. <form onSubmit={handleUpscale} className="space-y-4">
  180. <div className="space-y-2">
  181. <Label>Source Image *</Label>
  182. <div className="space-y-4">
  183. {previewImage && (
  184. <div className="relative">
  185. <img
  186. src={previewImage}
  187. alt="Source"
  188. className="w-full rounded-lg border border-border"
  189. />
  190. </div>
  191. )}
  192. <Button
  193. type="button"
  194. variant="outline"
  195. onClick={() => fileInputRef.current?.click()}
  196. className="w-full"
  197. >
  198. <Upload className="h-4 w-4" />
  199. {previewImage ? 'Change Image' : 'Upload Image'}
  200. </Button>
  201. <input
  202. ref={fileInputRef}
  203. type="file"
  204. accept="image/*"
  205. onChange={handleImageUpload}
  206. className="hidden"
  207. />
  208. </div>
  209. </div>
  210. <div className="space-y-2">
  211. <Label htmlFor="upscale_factor">Upscale Factor</Label>
  212. <select
  213. id="upscale_factor"
  214. name="upscale_factor"
  215. value={formData.upscale_factor}
  216. onChange={handleInputChange}
  217. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  218. >
  219. <option value={2}>2x (Double)</option>
  220. <option value={3}>3x (Triple)</option>
  221. <option value={4}>4x (Quadruple)</option>
  222. </select>
  223. <p className="text-xs text-muted-foreground">
  224. Higher factors take longer to process
  225. </p>
  226. </div>
  227. <div className="space-y-2">
  228. <Label htmlFor="model">Upscaling Model</Label>
  229. <select
  230. id="model"
  231. name="model"
  232. value={formData.model}
  233. onChange={handleInputChange}
  234. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  235. >
  236. {upscalerModels.length > 0 ? (
  237. upscalerModels.map((model) => (
  238. <option key={model.id} value={model.name}>
  239. {model.name}
  240. </option>
  241. ))
  242. ) : (
  243. <option value="">Loading models...</option>
  244. )}
  245. </select>
  246. {upscalerModels.length === 0 && !loading && (
  247. <p className="text-xs text-yellow-600 dark:text-yellow-400">
  248. No upscaler models found. Please add ESRGAN or upscaler models to your models directory.
  249. </p>
  250. )}
  251. </div>
  252. <div className="flex gap-2">
  253. <Button type="submit" disabled={loading || !formData.image} className="flex-1">
  254. {loading ? (
  255. <>
  256. <Loader2 className="h-4 w-4 animate-spin" />
  257. Upscaling...
  258. </>
  259. ) : (
  260. 'Upscale'
  261. )}
  262. </Button>
  263. {loading && (
  264. <Button type="button" variant="destructive" onClick={handleCancel}>
  265. <X className="h-4 w-4" />
  266. Cancel
  267. </Button>
  268. )}
  269. </div>
  270. {error && (
  271. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  272. {error}
  273. </div>
  274. )}
  275. {loading && jobInfo && (
  276. <div className="rounded-md bg-muted p-3 text-sm">
  277. <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
  278. <p>Status: {jobInfo.status}</p>
  279. {jobInfo.progress !== undefined && (
  280. <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
  281. )}
  282. </div>
  283. )}
  284. <div className="rounded-md bg-blue-500/10 p-3 text-sm text-blue-600 dark:text-blue-400">
  285. <p className="font-medium">Note</p>
  286. <p className="mt-1">
  287. Upscaling functionality depends on your backend configuration and available upscaler models.
  288. </p>
  289. </div>
  290. </form>
  291. </CardContent>
  292. </Card>
  293. {/* Right Panel - Upscaled Images */}
  294. <Card>
  295. <CardContent className="pt-6">
  296. <div className="space-y-4">
  297. <h3 className="text-lg font-semibold">Upscaled Image</h3>
  298. {generatedImages.length === 0 ? (
  299. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  300. <p className="text-muted-foreground">
  301. {loading ? 'Upscaling...' : 'Upscaled image will appear here'}
  302. </p>
  303. </div>
  304. ) : (
  305. <div className="grid gap-4">
  306. {generatedImages.map((image, index) => (
  307. <div key={index} className="relative group">
  308. <img
  309. src={image}
  310. alt={`Upscaled ${index + 1}`}
  311. className="w-full rounded-lg border border-border"
  312. />
  313. <Button
  314. size="icon"
  315. variant="secondary"
  316. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  317. onClick={() => {
  318. const authToken = localStorage.getItem('auth_token');
  319. const unixUser = localStorage.getItem('unix_user');
  320. downloadAuthenticatedImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`, authToken || undefined, unixUser || undefined)
  321. .catch(err => {
  322. console.error('Failed to download image:', err);
  323. // Fallback to regular download if authenticated download fails
  324. downloadImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`);
  325. });
  326. }}
  327. >
  328. <Download className="h-4 w-4" />
  329. </Button>
  330. </div>
  331. ))}
  332. </div>
  333. )}
  334. </div>
  335. </CardContent>
  336. </Card>
  337. </div>
  338. </div>
  339. </AppLayout>
  340. );
  341. }