page.tsx.backup2 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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/hooks';
  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. 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. <Card>
  258. <CardHeader>
  259. <CardTitle>Model Selection</CardTitle>
  260. <CardDescription>Select upscaler model for image enhancement</CardDescription>
  261. </CardHeader>
  262. <EnhancedModelSelect
  263. modelType="upscaler"
  264. label="Upscaling Model"
  265. description="Model to use for upscaling the image"
  266. value={selectedUpscalerModel}
  267. availableModels={upscalerModels}
  268. isAutoSelected={isUpscalerAutoSelected}
  269. isUserOverride={isUpscalerUserOverride}
  270. isLoading={state.isLoading}
  271. onValueChange={setSelectedUpscalerModel}
  272. onSetUserOverride={setUpscalerUserOverride}
  273. onClearOverride={clearUpscalerUserOverride}
  274. placeholder="Select an upscaler model"
  275. />
  276. <div className="flex gap-2">
  277. <Button type="submit" disabled={loading || !formData.image} className="flex-1">
  278. {loading ? (
  279. <>
  280. <Loader2 className="h-4 w-4 animate-spin" />
  281. Upscaling...
  282. </>
  283. ) : (
  284. 'Upscale'
  285. )}
  286. </Button>
  287. {loading && (
  288. <Button type="button" variant="destructive" onClick={handleCancel}>
  289. <X className="h-4 w-4" />
  290. Cancel
  291. </Button>
  292. )}
  293. </div>
  294. {error && (
  295. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  296. {error}
  297. </div>
  298. )}
  299. </form>
  300. </CardContent>
  301. </Card>
  302. <Card>
  303. <CardContent className="pt-6">
  304. <div className="space-y-4">
  305. <h3 className="text-lg font-semibold">Upscaled Image</h3>
  306. {generatedImages.length === 0 ? (
  307. <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
  308. <p className="text-muted-foreground">
  309. {loading ? 'Upscaling...' : 'Upscaled image will appear here'}
  310. </p>
  311. </div>
  312. ) : (
  313. <div className="grid gap-4">
  314. {generatedImages.map((image, index) => (
  315. <div key={index} className="relative group">
  316. <img
  317. src={image}
  318. alt={`Upscaled ${index + 1}`}
  319. className="w-full rounded-lg border border-border"
  320. />
  321. <Button
  322. size="icon"
  323. variant="secondary"
  324. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  325. onClick={() => {
  326. const authToken = localStorage.getItem('auth_token');
  327. const unixUser = localStorage.getItem('unix_user');
  328. downloadAuthenticatedImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`, authToken || undefined, unixUser || undefined)
  329. .catch(err => {
  330. console.error('Failed to download image:', err);
  331. // Fallback to regular download if authenticated download fails
  332. downloadImage(image, `upscaled-${Date.now()}-${formData.upscale_factor}x.png`);
  333. });
  334. }}
  335. >
  336. <Download className="h-4 w-4" />
  337. </Button>
  338. </div>
  339. ))}
  340. </div>
  341. )}
  342. </div>
  343. </CardContent>
  344. </Card>
  345. </div>
  346. </div>
  347. </AppLayout>
  348. );
  349. }
  350. export default function UpscalerPage() {
  351. return <UpscalerForm />;
  352. }