page.tsx 11 KB

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