Risma22 commited on
Commit
aefa7d6
Β·
verified Β·
1 Parent(s): c20004a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -89
app.py CHANGED
@@ -1,103 +1,80 @@
1
  import gradio as gr
2
  import torch
3
  import numpy as np
4
- from PIL import Image
5
  from transformers import AutoImageProcessor, AutoModel
6
- import os
7
-
8
- # =========================
9
- # Load model pretrained
10
- # =========================
11
- processor = AutoImageProcessor.from_pretrained(
12
- "google/vit-base-patch16-224"
13
- )
14
- model = AutoModel.from_pretrained(
15
- "google/vit-base-patch16-224"
16
- )
17
  model.eval()
18
 
19
- # =========================
20
- # Ekstraksi fitur
21
- # =========================
22
- def get_embedding(image):
23
  inputs = processor(images=image, return_tensors="pt")
24
  with torch.no_grad():
25
  outputs = model(**inputs)
26
- embedding = outputs.last_hidden_state.mean(dim=1)
27
- return embedding.squeeze().numpy()
28
-
29
- # =========================
30
- # Cosine similarity
31
- # =========================
32
- def cosine_similarity(a, b):
33
- return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
34
-
35
- # =========================
36
- # Fungsi utama
37
- # =========================
38
- def unsupervised_image_similarity(sample_path, test_path):
39
- if sample_path is None or test_path is None:
40
- return "❌ Silakan upload gambar sampling dan gambar uji."
41
-
42
- # Ambil nama file sampling
43
- sample_name = os.path.basename(sample_path)
44
-
45
- # Buka gambar
46
- img_sample = Image.open(sample_path).convert("RGB")
47
- img_test = Image.open(test_path).convert("RGB")
48
-
49
- # Ekstraksi embedding
50
- emb1 = get_embedding(img_sample)
51
- emb2 = get_embedding(img_test)
52
-
53
- similarity = cosine_similarity(emb1, emb2)
54
-
55
- # Threshold
56
- threshold = 0.75
57
-
58
- if similarity >= threshold:
59
- status = (
60
- f"βœ… GAMBAR UJI MEMILIKI KEMIRIPAN\n"
61
- f"dengan SAMPLING: **{sample_name}**"
62
- )
63
- else:
64
- status = (
65
- "❌ GAMBAR UJI TIDAK MEMILIKI KEMIRIPAN\n"
66
- "dengan sampling yang diinput"
67
- )
68
-
69
- hasil = f"""
70
- HASIL UNSUPERVISED LEARNING
71
-
72
- Nama sampling : {sample_name}
73
- Nilai kemiripan: {similarity:.2f}
74
-
75
- Keputusan:
76
- {status}
77
-
78
- Catatan:
79
- - Tidak menggunakan dataset
80
- - Tidak menggunakan label
81
- - Tidak melakukan training ulang
82
- - Pendekatan unsupervised berbasis similarity
83
- """
84
  return hasil
85
 
86
- # =========================
87
- # UI Gradio
88
- # =========================
89
- app = gr.Interface(
90
- fn=unsupervised_image_similarity,
91
- inputs=[
92
- gr.Image(type="filepath", label="Gambar Sampling"),
93
- gr.Image(type="filepath", label="Gambar Uji")
94
- ],
95
- outputs=gr.Textbox(label="Hasil Analisis"),
96
- title="🧠 Unsupervised Image Similarity dengan Nama Sampling",
97
- description=(
98
- "Aplikasi unsupervised learning untuk mengecek apakah gambar uji "
99
- "memiliki kemiripan dengan gambar sampling tertentu."
100
  )
101
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  app.launch()
 
 
1
  import gradio as gr
2
  import torch
3
  import numpy as np
4
+ from collections import defaultdict
5
  from transformers import AutoImageProcessor, AutoModel
6
+ from sklearn.metrics.pairwise import cosine_similarity
7
+
8
+ # Load model pretrained (visual embedding)
9
+ processor = AutoImageProcessor.from_pretrained("facebook/dino-vits16")
10
+ model = AutoModel.from_pretrained("facebook/dino-vits16")
 
 
 
 
 
 
11
  model.eval()
12
 
13
+ # Database: label -> list of features
14
+ feature_db = defaultdict(list)
15
+
16
+ def extract_feature(image):
17
  inputs = processor(images=image, return_tensors="pt")
18
  with torch.no_grad():
19
  outputs = model(**inputs)
20
+ return outputs.last_hidden_state.mean(dim=1).numpy()
21
+
22
+ def tambah_sampling(image, label):
23
+ if image is None or label.strip() == "":
24
+ return "❌ Gambar dan label wajib diisi"
25
+
26
+ feat = extract_feature(image)
27
+ feature_db[label].append(feat)
28
+
29
+ return f"βœ… Sampling ditambahkan untuk label '{label}' (total: {len(feature_db[label])})"
30
+
31
+ def tebak_gambar(image):
32
+ if image is None:
33
+ return "❌ Upload gambar terlebih dahulu"
34
+
35
+ if len(feature_db) == 0:
36
+ return "❌ Belum ada data sampling"
37
+
38
+ test_feat = extract_feature(image)
39
+
40
+ label_scores = {}
41
+ for label, feats in feature_db.items():
42
+ sims = cosine_similarity(test_feat, np.vstack(feats))
43
+ label_scores[label] = sims.mean() # rata-rata kemiripan
44
+
45
+ # Ambil label dengan skor tertinggi
46
+ pred_label = max(label_scores, key=label_scores.get)
47
+ skor = label_scores[pred_label]
48
+
49
+ hasil = "πŸ“Œ HASIL PREDIKSI (BERDASARKAN KEMIRIPAN)\n\n"
50
+ for lbl, sc in sorted(label_scores.items(), key=lambda x: x[1], reverse=True):
51
+ hasil += f"- {lbl}: {sc:.2f}\n"
52
+
53
+ hasil += f"\nβœ… Gambar PALING MIRIP dengan: **{pred_label}**"
54
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  return hasil
56
 
57
+ with gr.Blocks() as app:
58
+ gr.Markdown("## 🧠 Tebak Gambar Supervised (Similarity-Based)")
59
+ gr.Markdown(
60
+ "Upload gambar sampling dengan label, lalu upload gambar baru. "
61
+ "AI menentukan label berdasarkan kemiripan visual, bukan gambar yang sama persis."
 
 
 
 
 
 
 
 
 
62
  )
63
+
64
+ with gr.Tab("1️⃣ Tambah Data Sampling"):
65
+ img1 = gr.Image(type="pil", label="Gambar Sampling")
66
+ lbl = gr.Textbox(label="Label")
67
+ out1 = gr.Textbox(label="Status")
68
+ btn1 = gr.Button("Tambah")
69
+
70
+ btn1.click(tambah_sampling, [img1, lbl], out1)
71
+
72
+ with gr.Tab("2️⃣ Tebak Gambar"):
73
+ img2 = gr.Image(type="pil", label="Gambar Uji")
74
+ out2 = gr.Textbox(label="Hasil")
75
+ btn2 = gr.Button("Tebak")
76
+
77
+ btn2.click(tebak_gambar, img2, out2)
78
 
79
  app.launch()
80
+