page.tsx 15 KB

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