File size: 1,599 Bytes
60faa09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/lib/auth";
import { getHFStorageForUser } from "@/lib/storage/hf";

export async function GET(req) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const token = session.user.hfAccessToken;
    if (!token) {
      return NextResponse.json({
        datasets: [], files: [],
        note: "No HF access token. Sign in with HuggingFace to enable HF bucket storage.",
      });
    }

    const username = session.user.hfUsername;
    let datasets = [];
    try {
      const res = await fetch(
        `https://huggingface.co/api/datasets?author=${encodeURIComponent(username)}`,
        { headers: { Authorization: `Bearer ${token}` } },
      );
      if (res.ok) datasets = await res.json();
    } catch (e) {
      console.warn("[HF_DATASETS_LIST_FAILED]", e.message);
    }

    const subdir = new URL(req.url).searchParams.get("dir") || "uploads";
    const storage = getHFStorageForUser({ hfAccessToken: token, hfUsername: username });
    let files = [];
    if (storage) files = await storage.listFiles(`${subdir}/`);

    return NextResponse.json({
      datasets: datasets.map((d) => ({ id: d.id, name: d.name, private: d.private })),
      files,
      repo: storage?.repo || null,
    });
  } catch (error) {
    console.error("[HF_DATASETS_GET_ERROR]", error);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}