File size: 3,290 Bytes
eecbedf
 
 
 
4fc8652
 
 
 
 
 
eecbedf
 
 
 
 
 
 
 
 
 
 
 
 
 
4fc8652
 
eecbedf
 
 
4fc8652
 
 
 
 
eecbedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fc8652
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { NextRequest, NextResponse } from "next/server";
import { RepoDesignation, uploadFiles } from "@huggingface/hub";

import { isAuthenticated } from "@/lib/auth";
// Remove MongoDB imports since we're using local storage
// import Project from "@/models/Project";
// import dbConnect from "@/lib/mongodb";

// Import local storage functions
import { loadProject, saveProject } from "@/lib/local-storage";

// No longer need the ImageUpload interface since we're handling FormData with File objects

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ namespace: string; repoId: string }> }
) {
  try {
    const user = await isAuthenticated();

    if (user instanceof NextResponse || !user) {
      return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
    }

    // Remove MongoDB connection since we're using local storage
    // await dbConnect();
    const param = await params;
    const { namespace, repoId } = param;
    
    // Use local storage instead of MongoDB
    const projectId = `${namespace}/${repoId}`;
    const projectResult = await loadProject(projectId);
    
    if (!projectResult.success) {
      return NextResponse.json(
        {
          ok: false,
          error: "Project not found",
        },
        { status: 404 }
      );
    }

    // Parse the FormData to get the images
    const formData = await req.formData();
    const imageFiles = formData.getAll("images") as File[];

    if (!imageFiles || imageFiles.length === 0) {
      return NextResponse.json(
        {
          ok: false,
          error: "At least one image file is required under the 'images' key",
        },
        { status: 400 }
      );
    }

    const files: File[] = [];
    for (const file of imageFiles) {
      if (!(file instanceof File)) {
        return NextResponse.json(
          {
            ok: false,
            error: "Invalid file format - all items under 'images' key must be files",
          },
          { status: 400 }
        );
      }

      if (!file.type.startsWith('image/')) {
        return NextResponse.json(
          {
            ok: false,
            error: `File ${file.name} is not an image`,
          },
          { status: 400 }
        );
      }

      // Create File object with images/ folder prefix
      const fileName = `images/${file.name}`;
      const processedFile = new File([file], fileName, { type: file.type });
      files.push(processedFile);
    }

    // Upload files to HuggingFace space
    const repo: RepoDesignation = {
      type: "space",
      name: `${namespace}/${repoId}`,
    };

    await uploadFiles({
      repo,
      files,
      accessToken: user.token as string,
      commitTitle: `Upload ${files.length} image(s)`,
    });

    return NextResponse.json({ 
      ok: true, 
      message: `Successfully uploaded ${files.length} image(s) to ${namespace}/${repoId}/images/`,
      uploadedFiles: files.map((file) => `https://huggingface.co/spaces/${namespace}/${repoId}/resolve/main/${file.name}`),
    }, { status: 200 });

  } catch (error) {
    console.error('Error uploading images:', error);
    return NextResponse.json(
      {
        ok: false,
        error: "Failed to upload images",
      },
      { status: 500 }
    );
  }
}