page.tsx 16 KB

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