muhammadsalmanalfaridzi commited on
Commit
5a61493
·
verified ·
1 Parent(s): ae7d8a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -38
app.py CHANGED
@@ -1,56 +1,85 @@
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(46).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=60, overlap=80).json()
20
-
21
- # Menghitung jumlah objek per kelas
22
- class_count = {}
23
- total_count = 0
24
- for prediction in predictions['predictions']:
25
- class_name = prediction['class']
26
- if class_name in class_count:
27
- class_count[class_name] += 1
28
- else:
29
- class_count[class_name] = 1
30
- total_count += 1
31
-
32
- # Menyusun output berupa string hasil perhitungan
33
- result_text = "Product Nestle\n\n"
34
- for class_name, count in class_count.items():
35
- result_text += f"{class_name}: {count} objek\n"
36
-
37
- result_text += f"\nTotal Product Nestle: {total_count}"
38
-
39
- # Menyimpan gambar dengan prediksi
40
- output_image = model.predict(temp_file_path, confidence=60, overlap=80).save("/tmp/prediction.jpg")
41
-
 
 
 
 
 
 
 
 
42
  # Hapus file sementara setelah prediksi
43
  os.remove(temp_file_path)
44
 
45
- return "/tmp/prediction.jpg", result_text
46
 
47
- # Membuat antarmuka Gradio
48
- iface = gr.Interface(
49
- fn=detect_objects, # Fungsi yang dipanggil saat gambar diupload
50
- inputs=gr.Image(type="pil"), # Input berupa gambar
51
- outputs=[gr.Image(), gr.Textbox()], # Output gambar dan teks
52
- live=True # Menampilkan hasil secara langsung
53
- )
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
  # Menjalankan antarmuka
56
- iface.launch()
 
1
  import gradio as gr
2
+ from dotenv import load_dotenv
3
  from roboflow import Roboflow
4
  import tempfile
5
  import os
6
+ import requests
7
 
8
+ # Muat variabel lingkungan dari file .env
9
+ load_dotenv()
10
+ api_key = os.getenv("ROBOFLOW_API_KEY")
11
+ workspace = os.getenv("ROBOFLOW_WORKSPACE")
12
+ project_name = os.getenv("ROBOFLOW_PROJECT")
13
+ model_version = int(os.getenv("ROBOFLOW_MODEL_VERSION"))
14
+
15
+ # Inisialisasi Roboflow menggunakan data yang diambil dari secrets
16
+ rf = Roboflow(api_key=api_key)
17
+ project = rf.workspace(workspace).project(project_name)
18
+ model = project.version(model_version).model
19
 
20
  # Fungsi untuk menangani input dan output gambar
21
  def detect_objects(image):
22
+ # Simpan gambar yang diupload sebagai file sementara
23
  with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file:
24
  image.save(temp_file, format="JPEG")
25
  temp_file_path = temp_file.name
26
 
27
+ try:
28
+ # Lakukan prediksi pada gambar
29
+ predictions = model.predict(temp_file_path, confidence=60, overlap=80).json()
30
+
31
+ # Menghitung jumlah objek per kelas
32
+ class_count = {}
33
+ total_count = 0 # Menyimpan total jumlah objek
34
+
35
+ for prediction in predictions['predictions']:
36
+ class_name = prediction['class']
37
+ class_count[class_name] = class_count.get(class_name, 0) + 1
38
+ total_count += 1 # Tambah jumlah objek untuk setiap prediksi
39
+
40
+ # Menyusun output berupa string hasil perhitungan
41
+ result_text = "Product Nestle\n\n"
42
+ for class_name, count in class_count.items():
43
+ result_text += f"{class_name}: {count}\n"
44
+ result_text += f"\nTotal Product Nestle: {total_count}"
45
+
46
+ # Menyimpan gambar dengan prediksi
47
+ output_image_path = "/tmp/prediction.jpg"
48
+ model.predict(temp_file_path, confidence=60, overlap=80).save(output_image_path)
49
+
50
+ except requests.exceptions.HTTPError as http_err:
51
+ # Menangani kesalahan HTTP
52
+ result_text = f"HTTP error occurred: {http_err}"
53
+ output_image_path = temp_file_path # Kembalikan gambar asli jika terjadi error
54
+ except Exception as err:
55
+ # Menangani kesalahan lain
56
+ result_text = f"An error occurred: {err}"
57
+ output_image_path = temp_file_path # Kembalikan gambar asli jika terjadi error
58
+
59
  # Hapus file sementara setelah prediksi
60
  os.remove(temp_file_path)
61
 
62
+ return output_image_path, result_text
63
 
64
+ # Membuat antarmuka Gradio dengan tata letak fleksibel
65
+ with gr.Blocks() as iface:
66
+ with gr.Row():
67
+ with gr.Column():
68
+ input_image = gr.Image(type="pil", label="Input Image")
69
+ with gr.Column():
70
+ output_image = gr.Image(label="Detect Object")
71
+ with gr.Column():
72
+ output_text = gr.Textbox(label="Counting Object")
73
+
74
+ # Tombol untuk memproses input
75
+ detect_button = gr.Button("Detect")
76
+
77
+ # Hubungkan tombol dengan fungsi deteksi
78
+ detect_button.click(
79
+ fn=detect_objects,
80
+ inputs=input_image,
81
+ outputs=[output_image, output_text]
82
+ )
83
 
84
  # Menjalankan antarmuka
85
+ iface.launch()