Risma22 commited on
Commit
8f124a0
·
verified ·
1 Parent(s): e7a3768

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from sklearn.metrics.pairwise import cosine_similarity
7
+
8
+ # Load model pretrained (tanpa training ulang)
9
+ processor = AutoImageProcessor.from_pretrained("facebook/dino-vits16")
10
+ model = AutoModel.from_pretrained("facebook/dino-vits16")
11
+ model.eval()
12
+
13
+ # Simpan data sampling (memory sementara)
14
+ database_features = []
15
+ database_labels = []
16
+
17
+ def extract_feature(image):
18
+ inputs = processor(images=image, return_tensors="pt")
19
+ with torch.no_grad():
20
+ outputs = model(**inputs)
21
+ feature = outputs.last_hidden_state.mean(dim=1).numpy()
22
+ return feature
23
+
24
+ def tambah_sampling(image, label):
25
+ if image is None or label.strip() == "":
26
+ return "❌ Gambar dan label wajib diisi"
27
+
28
+ feature = extract_feature(image)
29
+ database_features.append(feature)
30
+ database_labels.append(label)
31
+
32
+ return f"✅ Sampling ditambahkan: {label}\nTotal data: {len(database_labels)}"
33
+
34
+ def prediksi_gambar(image):
35
+ if len(database_features) == 0:
36
+ return "❌ Belum ada data sampling"
37
+
38
+ feature = extract_feature(image)
39
+ similarities = cosine_similarity(feature, np.vstack(database_features))
40
+ idx = np.argmax(similarities)
41
+
42
+ label_pred = database_labels[idx]
43
+ skor = similarities[0][idx]
44
+
45
+ return f"📌 HASIL PREDIKSI:\n\nGambar paling mirip dengan: **{label_pred}**\nSkor kemiripan: {skor:.2f}"
46
+
47
+ with gr.Blocks(title="Supervised Tebak Gambar") as app:
48
+ gr.Markdown("## 🧠 Aplikasi Tebak Gambar (Supervised Learning)")
49
+ gr.Markdown(
50
+ "Upload gambar contoh (sampling) + label manual. "
51
+ "Kemudian upload gambar baru untuk diprediksi."
52
+ )
53
+
54
+ with gr.Tab("1️⃣ Tambah Data Sampling"):
55
+ img_sample = gr.Image(type="pil", label="Upload Gambar Sampling")
56
+ label_input = gr.Textbox(label="Label Gambar")
57
+ btn_add = gr.Button("Tambah ke Dataset")
58
+ output_add = gr.Textbox(label="Status")
59
+
60
+ btn_add.click(
61
+ tambah_sampling,
62
+ inputs=[img_sample, label_input],
63
+ outputs=output_add
64
+ )
65
+
66
+ with gr.Tab("2️⃣ Tebak Gambar"):
67
+ img_test = gr.Image(type="pil", label="Upload Gambar untuk Ditebak")
68
+ btn_pred = gr.Button("Tebak Gambar")
69
+ output_pred = gr.Textbox(label="Hasil Prediksi")
70
+
71
+ btn_pred.click(
72
+ prediksi_gambar,
73
+ inputs=img_test,
74
+ outputs=output_pred
75
+ )
76
+
77
+ app.launch()