page.tsx 15 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 } 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 [generatedImages, setGeneratedImages] = useState<string[]>([]);
  62. const [pollCleanup, setPollCleanup] = useState<(() => void) | null>(null);
  63. const fileInputRef = useRef<HTMLInputElement>(null);
  64. // Cleanup polling on unmount
  65. useEffect(() => {
  66. return () => {
  67. if (pollCleanup) {
  68. pollCleanup();
  69. }
  70. };
  71. }, [pollCleanup]);
  72. useEffect(() => {
  73. const loadModels = async () => {
  74. try {
  75. // Fetch all models with enhanced info
  76. const modelsData = await apiClient.getModels();
  77. // Filter for upscaler models (ESRGAN and upscaler types)
  78. const allUpscalerModels = [
  79. ...modelsData.models.filter((m) => m.type.toLowerCase() === "esrgan"),
  80. ...modelsData.models.filter(
  81. (m) => m.type.toLowerCase() === "upscaler",
  82. ),
  83. ];
  84. actions.setModels(modelsData.models);
  85. // Set first model as default if none selected
  86. if (allUpscalerModels.length > 0 && !formData.model) {
  87. setFormData((prev) => ({
  88. ...prev,
  89. model: allUpscalerModels[0].name,
  90. }));
  91. }
  92. } catch (err) {
  93. console.error("Failed to load upscaler models:", err);
  94. }
  95. };
  96. loadModels();
  97. }, [actions, formData.model, setFormData]);
  98. // Update form data when upscaler model changes
  99. useEffect(() => {
  100. if (selectedUpscalerModel) {
  101. setFormData((prev) => ({
  102. ...prev,
  103. model: selectedUpscalerModel,
  104. }));
  105. }
  106. }, [selectedUpscalerModel, setFormData]);
  107. const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
  108. const file = e.target.files?.[0];
  109. if (!file) return;
  110. try {
  111. const base64 = await fileToBase64(file);
  112. setUploadedImage(base64);
  113. setPreviewImage(base64);
  114. setError(null);
  115. } catch {
  116. setError("Failed to load image");
  117. }
  118. };
  119. const pollJobStatus = async (jobId: string) => {
  120. const maxAttempts = 300;
  121. let attempts = 0;
  122. let isPolling = true;
  123. let timeoutId: NodeJS.Timeout | null = null;
  124. const poll = async () => {
  125. if (!isPolling) return;
  126. try {
  127. const status: JobDetailsResponse = await apiClient.getJobStatus(jobId);
  128. setJobInfo(status.job);
  129. if (status.job.status === "completed") {
  130. let imageUrls: string[] = [];
  131. // Handle both old format (result.images) and new format (outputs)
  132. if (status.job.outputs && status.job.outputs.length > 0) {
  133. // New format: convert output URLs to authenticated image URLs with cache-busting
  134. imageUrls = status.job.outputs.map((output: { filename: string }) => {
  135. const filename = output.filename;
  136. return apiClient.getImageUrl(jobId, filename);
  137. });
  138. } else if (
  139. status.job.result?.images &&
  140. status.job.result.images.length > 0
  141. ) {
  142. // Old format: convert image URLs to authenticated URLs
  143. imageUrls = status.job.result.images.map((imageUrl: string) => {
  144. // Extract filename from URL if it's already a full URL
  145. if (imageUrl.includes("/output/")) {
  146. const parts = imageUrl.split("/output/");
  147. if (parts.length === 2) {
  148. const filename = parts[1].split("?")[0]; // Remove query params
  149. return apiClient.getImageUrl(jobId, filename);
  150. }
  151. }
  152. // If it's just a filename, convert it directly
  153. return apiClient.getImageUrl(jobId, imageUrl);
  154. });
  155. }
  156. // Create a new array to trigger React re-render
  157. setGeneratedImages([...imageUrls]);
  158. setLoading(false);
  159. isPolling = false;
  160. } else if (status.job.status === "failed") {
  161. setError(status.job.error || "Upscaling failed");
  162. setLoading(false);
  163. isPolling = false;
  164. } else if (status.job.status === "cancelled") {
  165. setError("Upscaling was cancelled");
  166. setLoading(false);
  167. isPolling = false;
  168. } else if (attempts < maxAttempts) {
  169. attempts++;
  170. timeoutId = setTimeout(poll, 2000);
  171. } else {
  172. setError("Job polling timeout");
  173. setLoading(false);
  174. isPolling = false;
  175. }
  176. } catch {
  177. if (isPolling) {
  178. setError("Failed to check job status");
  179. setLoading(false);
  180. isPolling = false;
  181. }
  182. }
  183. };
  184. poll();
  185. // Return cleanup function
  186. return () => {
  187. isPolling = false;
  188. if (timeoutId) {
  189. clearTimeout(timeoutId);
  190. }
  191. };
  192. };
  193. const handleUpscale = async (e: React.FormEvent) => {
  194. e.preventDefault();
  195. if (!uploadedImage) {
  196. setError("Please upload an image first");
  197. return;
  198. }
  199. setLoading(true);
  200. setError(null);
  201. setGeneratedImages([]);
  202. setJobInfo(null);
  203. try {
  204. // Validate model selection
  205. if (!selectedUpscalerModel) {
  206. setError("Please select an upscaler model");
  207. setLoading(false);
  208. return;
  209. }
  210. // Note: You may need to adjust the API endpoint based on your backend implementation
  211. const job = await apiClient.generateImage({
  212. prompt: `upscale ${formData.upscale_factor}x`,
  213. model: selectedUpscalerModel,
  214. // Add upscale-specific parameters here based on your API
  215. });
  216. setJobInfo(job);
  217. const jobId = job.request_id || job.id;
  218. if (jobId) {
  219. const cleanup = pollJobStatus(jobId);
  220. setPollCleanup(() => cleanup);
  221. } else {
  222. setError("No job ID returned from server");
  223. setLoading(false);
  224. }
  225. } catch {
  226. setError("Failed to upscale image");
  227. setLoading(false);
  228. }
  229. };
  230. const handleCancel = async () => {
  231. const jobId = jobInfo?.request_id || jobInfo?.id;
  232. if (jobId) {
  233. try {
  234. await apiClient.cancelJob(jobId);
  235. setLoading(false);
  236. setError("Upscaling cancelled");
  237. // Cleanup polling
  238. if (pollCleanup) {
  239. pollCleanup();
  240. setPollCleanup(null);
  241. }
  242. } catch (err) {
  243. console.error("Failed to cancel job:", err);
  244. }
  245. }
  246. };
  247. return (
  248. <AppLayout>
  249. <Header
  250. title="Upscaler"
  251. description="Enhance and upscale your images with AI"
  252. />
  253. <div className="container mx-auto p-6">
  254. <div className="grid gap-6 lg:grid-cols-2">
  255. {/* Left Panel - Form */}
  256. <Card>
  257. <CardContent className="pt-6">
  258. <form onSubmit={handleUpscale} className="space-y-4">
  259. <div className="space-y-2">
  260. <Label>Source Image *</Label>
  261. <div className="space-y-4">
  262. {previewImage && (
  263. <div className="relative">
  264. <img
  265. src={previewImage}
  266. alt="Preview"
  267. className="h-64 w-full rounded-lg object-cover"
  268. />
  269. <Button
  270. type="button"
  271. variant="destructive"
  272. size="icon"
  273. className="absolute top-2 right-2 h-8 w-8"
  274. onClick={() => {
  275. setPreviewImage(null);
  276. setUploadedImage("");
  277. }}
  278. >
  279. <X className="h-4 w-4" />
  280. </Button>
  281. </div>
  282. )}
  283. <div className="space-y-2">
  284. <div className="flex items-center justify-center">
  285. <input
  286. ref={fileInputRef}
  287. type="file"
  288. accept="image/*"
  289. onChange={handleImageUpload}
  290. className="hidden"
  291. />
  292. <Button
  293. type="button"
  294. variant="outline"
  295. onClick={() => fileInputRef.current?.click()}
  296. >
  297. <Upload className="mr-2 h-4 w-4" />
  298. Choose Image
  299. </Button>
  300. </div>
  301. </div>
  302. </div>
  303. </div>
  304. <div className="space-y-2">
  305. <Label>Upscaling Factor</Label>
  306. <select
  307. value={formData.upscale_factor}
  308. onChange={(e) =>
  309. setFormData((prev) => ({
  310. ...prev,
  311. upscale_factor: Number(e.target.value),
  312. }))
  313. }
  314. className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
  315. >
  316. <option value={2}>2x (Double)</option>
  317. <option value={3}>3x (Triple)</option>
  318. <option value={4}>4x (Quadruple)</option>
  319. </select>
  320. </div>
  321. <div className="space-y-2">
  322. <Label>Upscaler Model</Label>
  323. <Select
  324. value={formData.model}
  325. onValueChange={(value) => {
  326. setFormData((prev) => ({ ...prev, model: value }));
  327. setSelectedUpscalerModel(value);
  328. ;
  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. }