Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from roboflow import Roboflow
|
3 |
+
import tempfile
|
4 |
+
import os
|
5 |
+
|
6 |
+
# Inisialisasi Roboflow
|
7 |
+
rf = Roboflow(api_key="Otg64Ra6wNOgDyjuhMYU")
|
8 |
+
project = rf.workspace("alat-pelindung-diri").project("nescafe-4base")
|
9 |
+
model = project.version(16).model
|
10 |
+
|
11 |
+
# Fungsi untuk menangani input dan output gambar
|
12 |
+
def detect_objects(image):
|
13 |
+
# Menyimpan gambar yang diupload sebagai file sementara
|
14 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
|
15 |
+
image.save(temp_file, format="JPEG")
|
16 |
+
temp_file_path = temp_file.name
|
17 |
+
|
18 |
+
# Lakukan prediksi pada gambar
|
19 |
+
predictions = model.predict(temp_file_path, confidence=50, overlap=30).json()
|
20 |
+
|
21 |
+
# Menghitung jumlah objek per kelas
|
22 |
+
class_count = {}
|
23 |
+
for prediction in predictions['predictions']:
|
24 |
+
class_name = prediction['class']
|
25 |
+
if class_name in class_count:
|
26 |
+
class_count[class_name] += 1
|
27 |
+
else:
|
28 |
+
class_count[class_name] = 1
|
29 |
+
|
30 |
+
# Menyusun output berupa string hasil perhitungan
|
31 |
+
result_text = "Jumlah objek per kelas:\n"
|
32 |
+
for class_name, count in class_count.items():
|
33 |
+
result_text += f"{class_name}: {count} objek\n"
|
34 |
+
|
35 |
+
# Menyimpan gambar dengan prediksi
|
36 |
+
output_image = model.predict(temp_file_path, confidence=50, overlap=30).save("/tmp/prediction.jpg")
|
37 |
+
|
38 |
+
# Hapus file sementara setelah prediksi
|
39 |
+
os.remove(temp_file_path)
|
40 |
+
|
41 |
+
return "/tmp/prediction.jpg", result_text
|
42 |
+
|
43 |
+
# Membuat antarmuka Gradio
|
44 |
+
iface = gr.Interface(
|
45 |
+
fn=detect_objects, # Fungsi yang dipanggil saat gambar diupload
|
46 |
+
inputs=gr.Image(type="pil"), # Input berupa gambar
|
47 |
+
outputs=[gr.Image(), gr.Textbox()], # Output gambar dan teks
|
48 |
+
live=True # Menampilkan hasil secara langsung
|
49 |
+
)
|
50 |
+
|
51 |
+
# Menjalankan antarmuka
|
52 |
+
iface.launch()
|