page.tsx 15 KB

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