page.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. "use client";
  2. import { useState, useRef, useEffect, Suspense } from "react";
  3. import { useSearchParams } from "next/navigation";
  4. import { Button } from "@/components/ui/button";
  5. import { Input } from "@/components/ui/input";
  6. import { Label } from "@/components/ui/label";
  7. import {
  8. Card,
  9. CardContent,
  10. } from "@/components/ui/card";
  11. import {
  12. apiClient,
  13. type JobInfo,
  14. type JobDetailsResponse,
  15. type ModelInfo,
  16. type EnhancedModelsResponse,
  17. } from "@/lib/api";
  18. import { Loader2, Download, X, Upload } from "lucide-react";
  19. import {
  20. downloadAuthenticatedImage,
  21. fileToBase64,
  22. } from "@/lib/utils";
  23. import {
  24. Select,
  25. SelectContent,
  26. SelectItem,
  27. SelectTrigger,
  28. SelectValue,
  29. } from "@/components/ui/select";
  30. import { AppLayout, Header } from "@/components/layout";
  31. type UpscalerFormData = {
  32. upscale_factor: number;
  33. model: string;
  34. };
  35. const defaultFormData: UpscalerFormData = {
  36. upscale_factor: 2,
  37. model: "",
  38. };
  39. function UpscalerForm() {
  40. const searchParams = useSearchParams();
  41. // Simple state management - no complex hooks initially
  42. const [formData, setFormData] = useState<UpscalerFormData>(defaultFormData);
  43. // Separate state for image data (not stored in localStorage)
  44. const [uploadedImage, setUploadedImage] = useState<string>("");
  45. const [previewImage, setPreviewImage] = useState<string | null>(null);
  46. const [loading, setLoading] = useState(false);
  47. const [error, setError] = useState<string | null>(null);
  48. const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  49. const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  50. const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null);
  51. const fileInputRef = useRef<HTMLInputElement>(null);
  52. // URL input state
  53. const [urlInput, setUrlInput] = useState('');
  54. // Local state for upscaler models - no global context to avoid performance issues
  55. const [upscalerModels, setUpscalerModels] = useState<ModelInfo[]>([]);
  56. const [modelsLoading, setModelsLoading] = useState(false);
  57. // Cleanup polling on unmount
  58. useEffect(() => {
  59. return () => {
  60. if (pollCleanup) {
  61. pollCleanup();
  62. }
  63. };
  64. }, [pollCleanup]);
  65. // Load image from URL parameter on mount
  66. useEffect(() => {
  67. const imageUrl = searchParams.get('imageUrl');
  68. if (imageUrl) {
  69. loadImageFromUrl(imageUrl);
  70. }
  71. }, [searchParams]);
  72. // Load upscaler models on mount
  73. useEffect(() => {
  74. let isComponentMounted = true;
  75. const loadModels = async () => {
  76. try {
  77. setModelsLoading(true);
  78. setError(null);
  79. // Set up timeout for API call
  80. const timeoutPromise = new Promise((_, reject) =>
  81. setTimeout(() => reject(new Error('API call timeout')), 5000)
  82. );
  83. const apiPromise = apiClient.getModels("esrgan");
  84. const modelsData = await Promise.race([apiPromise, timeoutPromise]) as EnhancedModelsResponse;
  85. console.log("API call completed, models:", modelsData.models?.length || 0);
  86. if (!isComponentMounted) return;
  87. // Set models locally - no global state updates
  88. setUpscalerModels(modelsData.models || []);
  89. // Set first model as default if none selected
  90. if (modelsData.models?.length > 0 && !formData.model) {
  91. setFormData((prev) => ({
  92. ...prev,
  93. model: modelsData.models[0].name,
  94. }));
  95. }
  96. } catch (err) {
  97. console.error("Failed to load upscaler models:", err);
  98. if (isComponentMounted) {
  99. setError(`Failed to load upscaler models: ${err instanceof Error ? err.message : 'Unknown error'}`);
  100. }
  101. } finally {
  102. if (isComponentMounted) {
  103. setModelsLoading(false);
  104. }
  105. }
  106. };
  107. loadModels();
  108. return () => {
  109. isComponentMounted = false;
  110. };
  111. }, []); // eslint-disable-line react-hooks/exhaustive-deps
  112. const loadImageFromUrl = async (url: string) => {
  113. try {
  114. setError(null);
  115. // Fetch the image and convert to base64
  116. const response = await fetch(url);
  117. if (!response.ok) {
  118. throw new Error('Failed to fetch image');
  119. }
  120. const blob = await response.blob();
  121. const base64 = await new Promise<string>((resolve, reject) => {
  122. const reader = new FileReader();
  123. reader.onload = () => resolve(reader.result as string);
  124. reader.onerror = reject;
  125. reader.readAsDataURL(blob);
  126. });
  127. setUploadedImage(base64);
  128. setPreviewImage(base64);
  129. } catch (err) {
  130. console.error('Failed to load image from URL:', err);
  131. setError('Failed to load image from gallery');
  132. }
  133. };
  134. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  135. const file = e.target.files?.[0];
  136. if (!file) return;
  137. try {
  138. const base64 = await fileToBase64(file);
  139. setUploadedImage(base64);
  140. setPreviewImage(base64);
  141. setError(null);
  142. } catch {
  143. setError("Failed to load image");
  144. }
  145. };
  146. const pollJobStatus = async (jobId: string) => {
  147. const maxAttempts = 300;
  148. let attempts = 0;
  149. let isPolling = true;
  150. let timeoutId: NodeJS.Timeout | null = null;
  151. const poll = async () => {
  152. if (!isPolling) return;
  153. try {
  154. const status: JobDetailsResponse = await apiClient.getJobStatus(jobId);
  155. setJobInfo(status.job);
  156. if (status.job.status === "completed") {
  157. let imageUrls: string[] = [];
  158. // Handle both old format (result.images) and new format (outputs)
  159. if (status.job.outputs && status.job.outputs.length > 0) {
  160. // New format: convert output URLs to authenticated image URLs with cache-busting
  161. imageUrls = status.job.outputs.map((output: { filename: string }) => {
  162. const filename = output.filename;
  163. return apiClient.getImageUrl(jobId, filename);
  164. });
  165. } else if (
  166. status.job.result?.images &&
  167. status.job.result.images.length > 0
  168. ) {
  169. // Old format: convert image URLs to authenticated URLs
  170. imageUrls = status.job.result.images.map((imageUrl: string) => {
  171. // Extract filename from URL if it's already a full URL
  172. if (imageUrl.includes("/output/")) {
  173. const parts = imageUrl.split("/output/");
  174. if (parts.length === 2) {
  175. const filename = parts[1].split("?")[0]; // Remove query params
  176. return apiClient.getImageUrl(jobId, filename);
  177. }
  178. }
  179. // If it's just a filename, convert it directly
  180. return apiClient.getImageUrl(jobId, imageUrl);
  181. });
  182. }
  183. // Create a new array to trigger React re-render
  184. setGeneratedImages([...imageUrls]);
  185. setLoading(false);
  186. isPolling = false;
  187. } else if (status.job.status === "failed") {
  188. setError(status.job.error_message || status.job.error || "Upscaling failed");
  189. setLoading(false);
  190. isPolling = false;
  191. } else if (status.job.status === "cancelled") {
  192. setError("Upscaling was cancelled");
  193. setLoading(false);
  194. isPolling = false;
  195. } else if (attempts < maxAttempts) {
  196. attempts++;
  197. timeoutId = setTimeout(poll, 2000);
  198. } else {
  199. setError("Job polling timeout");
  200. setLoading(false);
  201. isPolling = false;
  202. }
  203. } catch {
  204. if (isPolling) {
  205. setError("Failed to check job status");
  206. setLoading(false);
  207. isPolling = false;
  208. }
  209. }
  210. };
  211. poll();
  212. // Return cleanup function
  213. return () => {
  214. isPolling = false;
  215. if (timeoutId) {
  216. clearTimeout(timeoutId);
  217. }
  218. };
  219. };
  220. const handleUpscale = async (e: React.FormEvent) => {
  221. e.preventDefault();
  222. if (!uploadedImage) {
  223. setError("Please upload an image first");
  224. return;
  225. }
  226. setLoading(true);
  227. setError(null);
  228. setGeneratedImages([]);
  229. setJobInfo(null);
  230. try {
  231. // Validate model selection
  232. if (!formData.model) {
  233. setError("Please select an upscaler model");
  234. setLoading(false);
  235. return;
  236. }
  237. // Unload all currently loaded models and load the selected upscaler model
  238. const selectedModel = upscalerModels.find(m => m.name === formData.model);
  239. const modelId = selectedModel?.id || selectedModel?.sha256;
  240. if (!selectedModel) {
  241. setError("Selected upscaler model not found.");
  242. setLoading(false);
  243. return;
  244. }
  245. if (!modelId) {
  246. setError("Selected upscaler model does not have a hash. Please compute the hash on the models page.");
  247. setLoading(false);
  248. return;
  249. }
  250. try {
  251. // Get all loaded models
  252. const loadedModels = await apiClient.getAllModels(undefined, true);
  253. // Unload all loaded models
  254. for (const model of loadedModels) {
  255. const unloadId = model.id || model.sha256;
  256. if (unloadId) {
  257. try {
  258. await apiClient.unloadModel(unloadId);
  259. } catch (unloadErr) {
  260. console.warn(`Failed to unload model ${model.name}:`, unloadErr);
  261. // Continue with others
  262. }
  263. }
  264. }
  265. // Load the selected upscaler model
  266. await apiClient.loadModel(modelId);
  267. } catch (modelErr) {
  268. console.error("Failed to prepare upscaler model:", modelErr);
  269. setError("Failed to prepare upscaler model. Please try again.");
  270. setLoading(false);
  271. return;
  272. }
  273. const job = await apiClient.upscale({
  274. image: uploadedImage,
  275. model: formData.model,
  276. upscale_factor: formData.upscale_factor,
  277. });
  278. setJobInfo(job);
  279. const jobId = job.request_id || job.id;
  280. if (jobId) {
  281. const cleanup = pollJobStatus(jobId);
  282. setPollCleanup(() => cleanup);
  283. } else {
  284. setError("No job ID returned from server");
  285. setLoading(false);
  286. }
  287. } catch {
  288. setError("Failed to upscale image");
  289. setLoading(false);
  290. }
  291. };
  292. const handleCancel = async () => {
  293. const jobId = jobInfo?.request_id || jobInfo?.id;
  294. if (jobId) {
  295. try {
  296. await apiClient.cancelJob(jobId);
  297. setLoading(false);
  298. setError("Upscaling cancelled");
  299. // Cleanup polling
  300. if (pollCleanup) {
  301. pollCleanup();
  302. setPollCleanup(null);
  303. }
  304. } catch (err) {
  305. console.error("Failed to cancel job:", err);
  306. }
  307. }
  308. };
  309. return (
  310. <AppLayout>
  311. <Header
  312. title="Upscaler"
  313. description="Enhance and upscale your images with AI"
  314. />
  315. <div className="container mx-auto p-6">
  316. <div className="grid gap-6 lg:grid-cols-2">
  317. {/* Left Panel - Form Parameters */}
  318. <div className="space-y-6">
  319. <Card>
  320. <CardContent className="pt-6">
  321. <form onSubmit={handleUpscale} className="space-y-4">
  322. {/* Image Upload Section */}
  323. <div className="space-y-2">
  324. <Label htmlFor="image-upload">Image *</Label>
  325. <div className="space-y-2">
  326. <input
  327. id="image-upload"
  328. type="file"
  329. accept="image/*"
  330. onChange={handleImageUpload}
  331. ref={fileInputRef}
  332. className="hidden"
  333. />
  334. <Button
  335. type="button"
  336. variant="outline"
  337. onClick={() => fileInputRef.current?.click()}
  338. className="w-full"
  339. >
  340. <Upload className="mr-2 h-4 w-4" />
  341. Choose Image File
  342. </Button>
  343. <div className="flex gap-2">
  344. <Input
  345. type="url"
  346. placeholder="Or paste image URL"
  347. value={urlInput}
  348. onChange={(e) => setUrlInput(e.target.value)}
  349. className="flex-1"
  350. />
  351. <Button
  352. type="button"
  353. variant="outline"
  354. onClick={() => loadImageFromUrl(urlInput)}
  355. disabled={!urlInput}
  356. >
  357. Load
  358. </Button>
  359. </div>
  360. </div>
  361. </div>
  362. {/* Model Selection */}
  363. <div className="space-y-2">
  364. <Label htmlFor="model">Upscaler Model</Label>
  365. <Select
  366. value={formData.model}
  367. onValueChange={(value) =>
  368. setFormData((prev) => ({ ...prev, model: value }))
  369. }
  370. >
  371. <SelectTrigger>
  372. <SelectValue placeholder="Select upscaler model" />
  373. </SelectTrigger>
  374. <SelectContent>
  375. {upscalerModels.map((model) => (
  376. <SelectItem key={model.name} value={model.name}>
  377. {model.name}
  378. </SelectItem>
  379. ))}
  380. </SelectContent>
  381. </Select>
  382. {modelsLoading && (
  383. <p className="text-sm text-muted-foreground">Loading models...</p>
  384. )}
  385. </div>
  386. {/* Upscale Factor */}
  387. <div className="space-y-2">
  388. <Label htmlFor="upscale_factor">
  389. Upscale Factor *
  390. <span className="text-xs text-muted-foreground ml-1">
  391. ({formData.upscale_factor}x)
  392. </span>
  393. </Label>
  394. <input
  395. id="upscale_factor"
  396. name="upscale_factor"
  397. type="range"
  398. min="2"
  399. max="8"
  400. step="1"
  401. value={formData.upscale_factor}
  402. onChange={(e) =>
  403. setFormData((prev) => ({
  404. ...prev,
  405. upscale_factor: Number(e.target.value),
  406. }))
  407. }
  408. className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700"
  409. />
  410. <div className="flex justify-between text-xs text-muted-foreground">
  411. <span>2x</span>
  412. <span>8x</span>
  413. </div>
  414. </div>
  415. {/* Generate Button */}
  416. <Button type="submit" disabled={loading || !uploadedImage} className="w-full">
  417. {loading ? (
  418. <>
  419. <Loader2 className="mr-2 h-4 w-4 animate-spin" />
  420. Upscaling...
  421. </>
  422. ) : (
  423. "Upscale Image"
  424. )}
  425. </Button>
  426. {/* Cancel Button */}
  427. {jobInfo && (
  428. <Button
  429. type="button"
  430. variant="outline"
  431. onClick={handleCancel}
  432. disabled={!loading}
  433. className="w-full"
  434. >
  435. <X className="h-4 w-4 mr-2" />
  436. Cancel
  437. </Button>
  438. )}
  439. {/* Error Display */}
  440. {error && (
  441. <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
  442. {error}
  443. </div>
  444. )}
  445. </form>
  446. </CardContent>
  447. </Card>
  448. </div>
  449. {/* Right Panel - Image Preview and Results */}
  450. <div className="space-y-6">
  451. {/* Image Preview */}
  452. <Card>
  453. <CardContent className="pt-6">
  454. <div className="space-y-4">
  455. <h3 className="text-lg font-semibold">Image Preview</h3>
  456. {previewImage ? (
  457. <div className="relative">
  458. <img
  459. src={previewImage}
  460. alt="Preview"
  461. className="w-full rounded-lg border border-border"
  462. />
  463. </div>
  464. ) : (
  465. <div className="flex h-64 items-center justify-center rounded-lg border-2 border-dashed border-border">
  466. <p className="text-muted-foreground">
  467. Upload an image to see preview
  468. </p>
  469. </div>
  470. )}
  471. </div>
  472. </CardContent>
  473. </Card>
  474. {/* Results */}
  475. <Card>
  476. <CardContent className="pt-6">
  477. <div className="space-y-4">
  478. <h3 className="text-lg font-semibold">Upscaled Images</h3>
  479. {generatedImages.length === 0 ? (
  480. <div className="flex h-64 items-center justify-center rounded-lg border-2 border-dashed border-border">
  481. <p className="text-muted-foreground">
  482. {loading
  483. ? "Upscaling in progress..."
  484. : "Upscaled images will appear here"}
  485. </p>
  486. </div>
  487. ) : (
  488. <div className="grid gap-4">
  489. {generatedImages.map((image, index) => (
  490. <div key={index} className="relative group">
  491. <img
  492. src={image}
  493. alt={`Upscaled ${index + 1}`}
  494. className="w-full rounded-lg border border-border"
  495. />
  496. <Button
  497. size="icon"
  498. variant="secondary"
  499. className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
  500. onClick={() => {
  501. const authToken =
  502. localStorage.getItem("auth_token");
  503. const unixUser = localStorage.getItem("unix_user");
  504. downloadAuthenticatedImage(
  505. image,
  506. `upscaled-${Date.now()}-${index}.png`,
  507. authToken || undefined,
  508. unixUser || undefined,
  509. ).catch((err) => {
  510. console.error("Failed to download image:", err);
  511. });
  512. }}
  513. >
  514. <Download className="h-4 w-4" />
  515. </Button>
  516. </div>
  517. ))}
  518. </div>
  519. )}
  520. </div>
  521. </CardContent>
  522. </Card>
  523. </div>
  524. </div>
  525. </div>
  526. </AppLayout>
  527. );
  528. }
  529. export default function UpscalerPage() {
  530. return (
  531. <Suspense fallback={<div>Loading...</div>}>
  532. <UpscalerForm />
  533. </Suspense>
  534. );
  535. }