page.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. 'use client';
  2. import { useState, useRef, useEffect } from 'react';
  3. import { Header } from '@/components/header';
  4. import { MainLayout } from '@/components/main-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, 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, ...upscalerMods];
  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' && status.result?.images) {
  84. setGeneratedImages(status.result.images);
  85. setLoading(false);
  86. } else if (status.status === 'failed') {
  87. setError(status.error || 'Upscaling failed');
  88. setLoading(false);
  89. } else if (status.status === 'cancelled') {
  90. setError('Upscaling was cancelled');
  91. setLoading(false);
  92. } else if (attempts < maxAttempts) {
  93. attempts++;
  94. setTimeout(poll, 1000);
  95. } else {
  96. setError('Job polling timeout');
  97. setLoading(false);
  98. }
  99. } catch (err) {
  100. setError(err instanceof Error ? err.message : 'Failed to check job status');
  101. setLoading(false);
  102. }
  103. };
  104. poll();
  105. };
  106. const handleUpscale = async (e: React.FormEvent) => {
  107. e.preventDefault();
  108. if (!formData.image) {
  109. setError('Please upload an image first');
  110. return;
  111. }
  112. setLoading(true);
  113. setError(null);
  114. setGeneratedImages([]);
  115. setJobInfo(null);
  116. try {
  117. // Note: You may need to adjust the API endpoint based on your backend implementation
  118. const job = await apiClient.generateImage({
  119. prompt: `upscale ${formData.upscale_factor}x`,
  120. // Add upscale-specific parameters here based on your API
  121. } as any);
  122. setJobInfo(job);
  123. const jobId = job.request_id || job.id;
  124. if (jobId) {
  125. await pollJobStatus(jobId);
  126. } else {
  127. setError('No job ID returned from server');
  128. setLoading(false);
  129. }
  130. } catch (err) {
  131. setError(err instanceof Error ? err.message : 'Failed to upscale image');
  132. setLoading(false);
  133. }
  134. };
  135. const handleCancel = async () => {
  136. const jobId = jobInfo?.request_id || jobInfo?.id;
  137. if (jobId) {
  138. try {
  139. await apiClient.cancelJob(jobId);
  140. setLoading(false);
  141. setError('Upscaling cancelled');
  142. } catch (err) {
  143. console.error('Failed to cancel job:', err);
  144. }
  145. }
  146. };
  147. return (
  148. <MainLayout>
  149. <Header title="Upscaler" description="Enhance and upscale your images with AI" />
  150. <div className="container mx-auto p-6">
  151. <div className="grid gap-6 lg:grid-cols-2">
  152. {/* Left Panel - Form */}
  153. <Card>
  154. <CardContent className="pt-6">
  155. <form onSubmit={handleUpscale} className="space-y-4">
  156. <div className="space-y-2">
  157. <Label>Source Image *</Label>
  158. <div className="space-y-4">
  159. {previewImage && (
  160. <div className="relative">
  161. <img
  162. src={previewImage}
  163. alt="Source"
  164. className="w-full rounded-lg border border-border"
  165. />
  166. </div>
  167. )}
  168. <Button
  169. type="button"
  170. variant="outline"
  171. onClick={() => fileInputRef.current?.click()}
  172. className="w-full"
  173. >
  174. <Upload className="h-4 w-4" />
  175. {previewImage ? 'Change Image' : 'Upload Image'}
  176. </Button>
  177. <input
  178. ref={fileInputRef}
  179. type="file"
  180. accept="image/*"
  181. onChange={handleImageUpload}
  182. className="hidden"
  183. />
  184. </div>
  185. </div>
  186. <div className="space-y-2">
  187. <Label htmlFor="upscale_factor">Upscale Factor</Label>
  188. <select
  189. id="upscale_factor"
  190. name="upscale_factor"
  191. value={formData.upscale_factor}
  192. onChange={handleInputChange}
  193. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  194. >
  195. <option value={2}>2x (Double)</option>
  196. <option value={3}>3x (Triple)</option>
  197. <option value={4}>4x (Quadruple)</option>
  198. </select>
  199. <p className="text-xs text-muted-foreground">
  200. Higher factors take longer to process
  201. </p>
  202. </div>
  203. <div className="space-y-2">
  204. <Label htmlFor="model">Upscaling Model</Label>
  205. <select
  206. id="model"
  207. name="model"
  208. value={formData.model}
  209. onChange={handleInputChange}
  210. className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  211. >
  212. {upscalerModels.length > 0 ? (
  213. upscalerModels.map((model) => (
  214. <option key={model.id} value={model.name}>
  215. {model.name}
  216. </option>
  217. ))
  218. ) : (
  219. <option value="">Loading models...</option>
  220. )}
  221. </select>
  222. {upscalerModels.length === 0 && !loading && (
  223. <p className="text-xs text-yellow-600 dark:text-yellow-400">
  224. No upscaler models found. Please add ESRGAN or upscaler models to your models directory.
  225. </p>
  226. )}
  227. </div>
  228. <div className="flex gap-2">
  229. <Button type="submit" disabled={loading || !formData.image} className="flex-1">
  230. {loading ? (
  231. <>
  232. <Loader2 className="h-4 w-4 animate-spin" />
  233. Upscaling...
  234. </>
  235. ) : (
  236. 'Upscale'
  237. )}
  238. </Button>
  239. {loading && (
  240. <Button type="button" variant="destructive" onClick={handleCancel}>
  241. <X className="h-4 w-4" />
  242. Cancel
  243. </Button>
  244. )}
  245. </div>
  246. {error && (
  247. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  248. {error}
  249. </div>
  250. )}
  251. {loading && jobInfo && (
  252. <div className="rounded-md bg-muted p-3 text-sm">
  253. <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
  254. <p>Status: {jobInfo.status}</p>
  255. {jobInfo.progress !== undefined && (
  256. <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
  257. )}
  258. </div>
  259. )}
  260. <div className="rounded-md bg-blue-500/10 p-3 text-sm text-blue-600 dark:text-blue-400">
  261. <p className="font-medium">Note</p>
  262. <p className="mt-1">
  263. Upscaling functionality depends on your backend configuration and available upscaler models.
  264. </p>
  265. </div>
  266. </form>
  267. </CardContent>
  268. </Card>
  269. {/* Right Panel - Upscaled Images */}
  270. <Card>
  271. <CardContent className="pt-6">
  272. <div className="space-y-4">
  273. <h3 className="text-lg font-semibold">Upscaled Image</h3>
  274. {generatedImages.length === 0 ? (
  275. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  276. <p className="text-muted-foreground">
  277. {loading ? 'Upscaling...' : 'Upscaled image will appear here'}
  278. </p>
  279. </div>
  280. ) : (
  281. <div className="grid gap-4">
  282. {generatedImages.map((image, index) => (
  283. <div key={index} className="relative group">
  284. <img
  285. src={image}
  286. alt={`Upscaled ${index + 1}`}
  287. className="w-full rounded-lg border border-border"
  288. />
  289. <Button
  290. size="icon"
  291. variant="secondary"
  292. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  293. onClick={() => downloadImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`)}
  294. >
  295. <Download className="h-4 w-4" />
  296. </Button>
  297. </div>
  298. ))}
  299. </div>
  300. )}
  301. </div>
  302. </CardContent>
  303. </Card>
  304. </div>
  305. </div>
  306. </MainLayout>
  307. );
  308. }