File size: 2,395 Bytes
ea3f4d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { HF_TOKEN } from "$env/static/private";
import { json, error } from "@sveltejs/kit";

if (!HF_TOKEN) {
  console.error("HF_TOKEN environment variable not set.");
  throw error(500, "Server configuration error: Missing API Token");
}

/** @type {import('./$types').RequestHandler} */
export async function POST({ request }) {
  const { query } = await request.json();
  if (!query) {
    throw error(400, "Missing search query in request body");
  }

  console.log(`API: Searching Fal LoRAs for query: "${query}"`);
  const searchParams = new URLSearchParams({
    filter: "lora",
    limit: "1000", // Increase limit slightly for UI
    config: "false",
    full: "true",
    inference_provider: "fal-ai",
    search: query,
  });
  const url = `https://huggingface.co/api/models?${searchParams.toString()}`;

  try {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${HF_TOKEN}` },
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`Hugging Face API Error: ${response.status} ${errorText}`);
      throw error(
        response.status,
        `Error fetching LoRAs from Hugging Face: ${errorText}`
      );
    }

    const data = await response.json();
    const loras = data.map((model) => {
      // Find the first image file in siblings for the thumbnail
      const imageSibling = model.siblings?.find((sibling) =>
        /\.(png|jpg|jpeg|webp)$/i.test(sibling.rfilename)
      );

      const thumbnailUrl = imageSibling
        ? `https://huggingface.co/${model.modelId}/resolve/main/${imageSibling.rfilename}`
        : null; // Or a default placeholder image URL

      if (!thumbnailUrl) {
        const thumbnailUrl =
          "https://huggingface.co/front/assets/huggingface_logo-noborder.svg";
      }

      return {
        id: model.modelId,
        author: model.author,
        thumbnail: thumbnailUrl,
        // Add other fields if needed later
      };
    });

    console.log(
      "API: Returning LoRAs:",
      JSON.stringify(loras.slice(0, 5), null, 2)
    ); // Log first 5 results

    return json(loras);
  } catch (err) {
    console.error("Error in /api/search-loras:", err);
    // Throw SvelteKit error to ensure proper HTTP response
    if (err.status) throw err; // Re-throw SvelteKit errors
    throw error(500, "Internal Server Error");
  }
}