File size: 2,256 Bytes
81573bf
e8d1d73
81573bf
 
 
 
 
 
 
 
421e8cb
81573bf
 
421e8cb
81573bf
 
 
421e8cb
 
 
 
 
81573bf
421e8cb
81573bf
 
421e8cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81573bf
 
 
 
 
 
421e8cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81573bf
421e8cb
81573bf
 
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
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI Image Classifier</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

  <div class="card">
    <h1>πŸ–ΌοΈ AI Image Classifier</h1>
    <p>Upload an image and let AI identify it!</p>

    <input type="file" id="imageInput" accept="image/*">

    <br><br>

    <button id="classifyBtn">πŸ” Classify Image</button>

    <p id="status">⏳ Loading AI model...</p>

    <div id="result"></div>
  </div>

  <script type="module">
    import { pipeline }
      from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";

    let classifier;

    const status = document.getElementById("status");
    const button = document.getElementById("classifyBtn");
    const input = document.getElementById("imageInput");
    const result = document.getElementById("result");

    button.disabled = true;

    async function loadModel() {
      try {
        status.innerText = "⏳ Loading AI model... Please wait.";

        classifier = await pipeline(
          "image-classification",
          "Xenova/vit-base-patch16-224"
        );

        status.innerText = "βœ… AI model loaded! Upload an image.";
        button.disabled = false;

      } catch (error) {
        status.innerText = "❌ Model failed to load.";
        console.error(error);
      }
    }

    button.addEventListener("click", async () => {

      if (!input.files.length) {
        result.innerText = "⚠️ Please upload an image first.";
        return;
      }

      try {
        button.disabled = true;
        result.innerText = "πŸ€– AI is analyzing your image...";

        const image = input.files[0];

        const output = await classifier(image, {
          top_k: 3
        });

        result.innerHTML = `
          <h3>🎯 Results</h3>
          ${output.map(item =>
            `<p><b>${item.label}</b> β€” ${(item.score * 100).toFixed(2)}%</p>`
          ).join("")}
        `;

      } catch (error) {
        result.innerText = "❌ Something went wrong.";
        console.error(error);

      } finally {
        button.disabled = false;
      }
    });

    loadModel();
  </script>

</body>
</html>