page.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. 'use client';
  2. import { useState, useRef, 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 { Label } from '@/components/ui/label';
  8. import { Card, CardContent, CardHeader, CardTitle, CardDescription } 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/storage';
  13. import { ModelSelectionProvider, useModelSelection, useModelTypeSelection } from '@/contexts/model-selection-context';
  14. import { EnhancedModelSelect } from '@/components/features/models';
  15. // import { AutoSelectionStatus } from '@/components/features/models';
  16. type UpscalerFormData = {
  17. upscale_factor: number;
  18. model: string;
  19. };
  20. const defaultFormData: UpscalerFormData = {
  21. upscale_factor: 2,
  22. model: '',
  23. };
  24. function UpscalerForm() {
  25. const { state, actions } = useModelSelection();
  26. const {
  27. availableModels: upscalerModels,
  28. selectedModel: selectedUpscalerModel,
  29. isUserOverride: isUpscalerUserOverride,
  30. isAutoSelected: isUpscalerAutoSelected,
  31. setSelectedModel: setSelectedUpscalerModel,
  32. setUserOverride: setUpscalerUserOverride,
  33. clearUserOverride: clearUpscalerUserOverride,
  34. } = useModelTypeSelection('upscaler');
  35. const [formData, setFormData] = useLocalStorage<UpscalerFormData>(
  36. 'upscaler-form-data',
  37. defaultFormData,
  38. { excludeLargeData: true, maxSize: 512 * 1024 }
  39. );
  40. // Separate state for image data (not stored in localStorage)
  41. const [uploadedImage, setUploadedImage] = useState<string>('');
  42. const [previewImage, setPreviewImage] = useState<string | null>(null);
  43. const [loading, setLoading] = useState(false);
  44. const [error, setError] = useState<string | null>(null);
  45. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  46. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  47. const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null);
  48. const fileInputRef = useRef<HTMLInputElement>(null);
  49. // Cleanup polling on unmount
  50. useEffect(() => {
  51. return () => {
  52. if (pollCleanup) {
  53. pollCleanup();
  54. }
  55. };
  56. }, [pollCleanup]);
  57. useEffect(() => {
  58. const loadModels = async () => {
  59. try {
  60. // Fetch all models with enhanced info
  61. const modelsData = await apiClient.getModels();
  62. // Filter for upscaler models (ESRGAN and upscaler types)
  63. const allUpscalerModels = [
  64. ...modelsData.models.filter(m => m.type.toLowerCase() === 'esrgan'),
  65. ...modelsData.models.filter(m => m.type.toLowerCase() === 'upscaler')
  66. ];
  67. actions.setModels(modelsData.models);
  68. // Set first model as default if none selected
  69. if (allUpscalerModels.length > 0 && !formData.model) {
  70. setFormData(prev => ({ ...prev, model: allUpscalerModels[0].name }));
  71. }
  72. } catch (err) {
  73. console.error('Failed to load upscaler models:', err);
  74. }
  75. };
  76. loadModels();
  77. }, [actions, formData.model, setFormData]);
  78. // Update form data when upscaler model changes
  79. useEffect(() => {
  80. if (selectedUpscalerModel) {
  81. setFormData(prev => ({
  82. ...prev,
  83. model: selectedUpscalerModel,
  84. }));
  85. }
  86. }, [selectedUpscalerModel, setFormData]);
  87. const handleInputChange = (
  88. e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>
  89. ) => {
  90. const { name, value } = e.target;
  91. setFormData((prev) => ({
  92. ...prev,
  93. [name]: name === 'upscale_factor' ? Number(value) : value,
  94. }));
  95. };
  96. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  97. const file = e.target.files?.[0];
  98. if (!file) return;
  99. try {
  100. const base64 = await fileToBase64(file);
  101. setUploadedImage(base64);
  102. setPreviewImage(base64);
  103. setError(null);
  104. } catch (err) {
  105. setError('Failed to load image');
  106. }
  107. };
  108. const pollJobStatus = async (jobId: string) => {
  109. const maxAttempts = 300;
  110. let attempts = 0;
  111. let isPolling = true;
  112. const poll = async () => {
  113. if (!isPolling) return;
  114. try {
  115. const status = await apiClient.getJobStatus(jobId);
  116. setJobInfo(status);
  117. if (status.status === 'completed') {
  118. let imageUrls: string[] = [];
  119. // Handle both old format (result.images) and new format (outputs)
  120. if (status.outputs && status.outputs.length > 0) {
  121. // New format: convert output URLs to authenticated image URLs with cache-busting
  122. imageUrls = status.outputs.map((output: any) => {
  123. const filename = output.filename;
  124. return apiClient.getImageUrl(jobId, filename);
  125. });
  126. } else if (status.result?.images && status.result.images.length > 0) {
  127. // Old format: convert image URLs to authenticated URLs
  128. imageUrls = status.result.images.map((imageUrl: string) => {
  129. // Extract filename from URL if it's already a full URL
  130. if (imageUrl.includes('/output/')) {
  131. const parts = imageUrl.split('/output/');
  132. if (parts.length === 2) {
  133. const filename = parts[1].split('?')[0]; // Remove query params
  134. return apiClient.getImageUrl(jobId, filename);
  135. }
  136. }
  137. // If it's just a filename, convert it directly
  138. return apiClient.getImageUrl(jobId, imageUrl);
  139. });
  140. }
  141. // Create a new array to trigger React re-render
  142. setGeneratedImages([...imageUrls]);
  143. setLoading(false);
  144. isPolling = false;
  145. } else if (status.status === 'failed') {
  146. setError(status.error || 'Upscaling failed');
  147. setLoading(false);
  148. isPolling = false;
  149. } else if (status.status === 'cancelled') {
  150. setError('Upscaling was cancelled');
  151. setLoading(false);
  152. isPolling = false;
  153. } else if (attempts < maxAttempts) {
  154. attempts++;
  155. setTimeout(poll, 2000);
  156. } else {
  157. setError('Job polling timeout');
  158. setLoading(false);
  159. isPolling = false;
  160. }
  161. } catch (err) {
  162. if (isPolling) {
  163. setError(err instanceof Error ? err.message : 'Failed to check job status');
  164. setLoading(false);
  165. isPolling = false;
  166. }
  167. }
  168. };
  169. poll();
  170. // Return cleanup function
  171. return () => {
  172. isPolling = false;
  173. };
  174. };
  175. const handleUpscale = async (e: React.FormEvent) => {
  176. e.preventDefault();
  177. if (!uploadedImage) {
  178. setError('Please upload an image first');
  179. return;
  180. }
  181. setLoading(true);
  182. setError(null);
  183. setGeneratedImages([]);
  184. setJobInfo(null);
  185. try {
  186. // Validate model selection
  187. if (!selectedUpscalerModel) {
  188. setError('Please select an upscaler model');
  189. setLoading(false);
  190. return;
  191. }
  192. // Note: You may need to adjust the API endpoint based on your backend implementation
  193. const job = await apiClient.generateImage({
  194. prompt: `upscale ${formData.upscale_factor}x`,
  195. model: selectedUpscalerModel,
  196. image: uploadedImage,
  197. // Add upscale-specific parameters here based on your API
  198. } as any);
  199. setJobInfo(job);
  200. const jobId = job.request_id || job.id;
  201. if (jobId) {
  202. const cleanup = pollJobStatus(jobId);
  203. setPollCleanup(() => cleanup);
  204. } else {
  205. setError('No job ID returned from server');
  206. setLoading(false);
  207. }
  208. } catch (err) {
  209. setError(err instanceof Error ? err.message : 'Failed to upscale image');
  210. setLoading(false);
  211. }
  212. };
  213. const handleCancel = async () => {
  214. const jobId = jobInfo?.request_id || jobInfo?.id;
  215. if (jobId) {
  216. try {
  217. await apiClient.cancelJob(jobId);
  218. setLoading(false);
  219. setError('Upscaling cancelled');
  220. // Cleanup polling
  221. if (pollCleanup) {
  222. pollCleanup();
  223. setPollCleanup(null);
  224. }
  225. } catch (err) {
  226. console.error('Failed to cancel job:', err);
  227. }
  228. }
  229. };
  230. return (
  231. <AppLayout>
  232. <Header title="Upscaler" description="Enhance and upscale your images with AI" />
  233. <div className="container mx-auto p-6">
  234. <div className="grid gap-6 lg:grid-cols-2">
  235. {/* Left Panel - Form */}
  236. <Card>
  237. <CardContent className="pt-6">
  238. <form onSubmit={handleUpscale} className="space-y-4">
  239. <div className="space-y-2">
  240. <Label>Source Image *</Label>
  241. <div className="space-y-4">
  242. {previewImage && (
  243. <div className="relative">
  244. <img
  245. src={previewImage}
  246. alt="Preview"
  247. className="h-64 w-full rounded-lg object-cover"
  248. />
  249. <Button
  250. type="button"
  251. variant="destructive"
  252. size="icon"
  253. className="absolute top-2 right-2 h-8 w-8"
  254. onClick={() => {
  255. setPreviewImage(null);
  256. setUploadedImage('');
  257. }}
  258. >
  259. <X className="h-4 w-4" />
  260. </Button>
  261. </div>
  262. )}
  263. <div className="space-y-2">
  264. <div className="flex items-center justify-center">
  265. <input
  266. ref={fileInputRef}
  267. type="file"
  268. accept="image/*"
  269. onChange={handleImageUpload}
  270. className="hidden"
  271. />
  272. <Button
  273. type="button"
  274. variant="outline"
  275. onClick={() => fileInputRef.current?.click()}
  276. >
  277. <Upload className="mr-2 h-4 w-4" />
  278. Choose Image
  279. </Button>
  280. </div>
  281. </div>
  282. </div>
  283. </div>
  284. <div className="space-y-2">
  285. <Label>Upscaling Factor</Label>
  286. <select
  287. value={formData.upscale_factor}
  288. onChange={(e) => setFormData(prev => ({ ...prev, upscale_factor: Number(e.target.value) }))}
  289. className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  290. >
  291. <option value={2}>2x (Double)</option>
  292. <option value={3}>3x (Triple)</option>
  293. <option value={4}>4x (Quadruple)</option>
  294. </select>
  295. </div>
  296. <div className="space-y-2">
  297. <Label>Upscaler Model</Label>
  298. <EnhancedModelSelect
  299. modelType="upscaler"
  300. label="Upscaling Model"
  301. value={formData.model}
  302. onValueChange={(value) => setFormData(prev => ({ ...prev, model: value }))}
  303. onSetUserOverride={(value) => {/* User override logic */}}
  304. onClearOverride={clearUpscalerUserOverride}
  305. availableModels={upscalerModels}
  306. isAutoSelected={isUpscalerAutoSelected}
  307. isUserOverride={isUpscalerUserOverride}
  308. placeholder="Select an upscaler model"
  309. />
  310. </div>
  311. <div className="flex gap-2">
  312. <Button type="submit" disabled={loading || !uploadedImage} className="flex-1">
  313. {loading ? (
  314. <>
  315. <Loader2 className="h-4 w-4 animate-spin" />
  316. Upscaling...
  317. </>
  318. ) : (
  319. 'Upscale'
  320. )}
  321. </Button>
  322. {loading && (
  323. <Button type="button" variant="destructive" onClick={handleCancel}>
  324. <X className="h-4 w-4" />
  325. Cancel
  326. </Button>
  327. )}
  328. </div>
  329. {error && (
  330. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  331. {error}
  332. </div>
  333. )}
  334. </form>
  335. </CardContent>
  336. </Card>
  337. <Card>
  338. <CardContent className="pt-6">
  339. <div className="space-y-4">
  340. <h3 className="text-lg font-semibold">Upscaled Image</h3>
  341. {generatedImages.length === 0 ? (
  342. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  343. <p className="text-muted-foreground">
  344. {loading ? 'Upscaling...' : 'Upscaled image will appear here'}
  345. </p>
  346. </div>
  347. ) : (
  348. <div className="grid gap-4">
  349. {generatedImages.map((image, index) => (
  350. <div key={index} className="relative group">
  351. <img
  352. src={image}
  353. alt={`Upscaled ${index + 1}`}
  354. className="w-full rounded-lg border border-border"
  355. />
  356. <Button
  357. size="icon"
  358. variant="secondary"
  359. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  360. onClick={() => {
  361. const authToken = localStorage.getItem('auth_token');
  362. const unixUser = localStorage.getItem('unix_user');
  363. downloadAuthenticatedImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`, authToken || undefined, unixUser || undefined)
  364. .catch(err => {
  365. console.error('Failed to download image:', err);
  366. // Fallback to regular download if authenticated download fails
  367. downloadImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`);
  368. });
  369. }}
  370. >
  371. <Download className="h-4 w-4" />
  372. </Button>
  373. </div>
  374. ))}
  375. </div>
  376. )}
  377. </div>
  378. </CardContent>
  379. </Card>
  380. </div>
  381. </div>
  382. </AppLayout>
  383. );
  384. }
  385. export default function UpscalerPage() {
  386. return <UpscalerForm />;
  387. }