superuser-aisensum commited on
Commit
656730d
·
verified ·
1 Parent(s): 2ffc4e1

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dotenv import load_dotenv
3
+ from roboflow import Roboflow
4
+ import tempfile
5
+ import os
6
+
7
+ # Muat variabel lingkungan dari file .env
8
+ load_dotenv()
9
+ api_key = os.getenv("ROBOFLOW_API_KEY")
10
+ workspace = os.getenv("ROBOFLOW_WORKSPACE")
11
+ project_name = os.getenv("ROBOFLOW_PROJECT")
12
+ model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
13
+
14
+ # Inisialisasi Roboflow menggunakan data yang diambil dari secrets
15
+ rf = Roboflow(api_key=api_key)
16
+ project = rf.workspace(workspace).project(project_name)
17
+ model = project.version(model_version).model
18
+
19
+ # Fungsi untuk menangani input dan output gambar
20
+ def detect_objects(image):
21
+ # Simpan gambar yang diupload sebagai file sementara
22
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
23
+ image.save(temp_file, format="JPEG")
24
+ temp_file_path = temp_file.name
25
+
26
+ # Lakukan prediksi pada gambar
27
+ predictions = model.predict(temp_file_path, confidence=60, overlap=80).json()
28
+
29
+ # Menghitung jumlah objek per kelas
30
+ class_count = {}
31
+ total_count = 0 # Menyimpan total jumlah objek
32
+
33
+ for prediction in predictions['predictions']:
34
+ class_name = prediction['class']
35
+ if class_name in class_count:
36
+ class_count[class_name] += 1
37
+ else:
38
+ class_count[class_name] = 1
39
+ total_count += 1 # Tambah jumlah objek untuk setiap prediksi
40
+
41
+ # Menyusun output berupa string hasil perhitungan
42
+ result_text = "Product Nestle \n"
43
+
44
+ for class_name, count in class_count.items():
45
+ result_text += f"{class_name}: {count} \n"
46
+
47
+ result_text += f"\nTotal Product Nestle: {total_count}"
48
+
49
+ # Menyimpan gambar dengan prediksi
50
+ output_image = model.predict(temp_file_path, confidence=60, overlap=80).save("/tmp/prediction.jpg")
51
+
52
+ # Hapus file sementara setelah prediksi
53
+ os.remove(temp_file_path)
54
+
55
+ return "/tmp/prediction.jpg", result_text
56
+
57
+ # Membuat antarmuka Gradio
58
+ iface = gr.Interface(
59
+ fn=detect_objects, # Fungsi yang dipanggil saat gambar diupload
60
+ inputs=gr.Image(type="pil"), # Input berupa gambar
61
+ outputs=[gr.Image(), gr.Textbox()], # Output gambar dan teks
62
+ live=True # Menampilkan hasil secara langsung
63
+ )
64
+
65
+ # Menjalankan antarmuka
66
+ iface.launch()