candenizkocak commited on
Commit
01034f9
·
verified ·
1 Parent(s): 88cf87e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -0
app.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import requests
4
+ from PIL import Image
5
+ import os
6
+
7
+ # --- Constants for the API ---
8
+ API_URL = "https://predict.ultralytics.com"
9
+ # It's recommended to use Hugging Face secrets for API keys
10
+ API_KEY = os.environ.get("ULTRALYTICS_API_KEY")
11
+ MODEL_ID = "https://hub.ultralytics.com/models/RsLHnWMhiBPqy3iFZAgr"
12
+
13
+ def classify_image(image):
14
+ """
15
+ Takes an image, sends it to the Ultralytics API, and returns the classification.
16
+ """
17
+ # Convert the Gradio image (numpy array) to a file-like object
18
+ image_pil = Image.fromarray(image)
19
+ image_path = "temp_image.jpg"
20
+ image_pil.save(image_path)
21
+
22
+ headers = {"x-api-key": API_KEY}
23
+ data = {
24
+ "model": MODEL_ID,
25
+ "imgsz": 640,
26
+ "conf": 0.25,
27
+ "iou": 0.45
28
+ }
29
+
30
+ try:
31
+ with open(image_path, "rb") as f:
32
+ response = requests.post(API_URL, headers=headers, data=data, files={"file": f})
33
+
34
+ # Check for a successful response
35
+ response.raise_for_status()
36
+
37
+ # Return the JSON response from the API
38
+ return response.json()
39
+
40
+ except requests.exceptions.RequestException as e:
41
+ return f"API Request Error: {e}"
42
+ finally:
43
+ # Clean up the temporary image file
44
+ if os.path.exists(image_path):
45
+ os.remove(image_path)
46
+
47
+ # --- Gradio Interface ---
48
+
49
+ # Define the input and output components
50
+ image_input = gr.Image(type="numpy", label="Upload an Image or Use Webcam")
51
+ json_output = gr.JSON(label="Classification Results")
52
+
53
+ # List of example images
54
+ example_images = [
55
+ ["images/img1.jpg"],
56
+ ["images/img2.jpg"],
57
+ ["images/img3.jpg"],
58
+ ["images/img4.jpg"],
59
+ ["images/img5.jpg"],
60
+ ]
61
+
62
+ # Create the Gradio interface
63
+ iface = gr.Interface(
64
+ fn=classify_image,
65
+ inputs=image_input,
66
+ outputs=json_output,
67
+ title="Image Classification with Ultralytics API",
68
+ description="Upload a picture or use your camera to classify an image using a pre-trained model. The results from the API will be displayed in JSON format.",
69
+ examples=example_images
70
+ )
71
+
72
+ # Launch the application
73
+ iface.launch()