Sina Media Lab commited on
Commit
2cfaaa4
ยท
1 Parent(s): 50d3e05

Update Gradio to latest secure version 3

Browse files
Files changed (3) hide show
  1. README.md +9 -5
  2. app.py +34 -18
  3. requirements.txt +5 -3
README.md CHANGED
@@ -11,19 +11,19 @@ pinned: false
11
 
12
  # ๐ŸŒธ Iris Detector
13
 
14
- A simple Gradio Space that predicts iris species using a K-Nearest Neighbors classifier (k=5).
15
 
16
  ## Features
17
  - 4 numeric inputs: sepal length, sepal width, petal length, petal width
18
  - Predicts one of 3 classes: `setosa`, `versicolor`, `virginica`
19
  - Shows probability distribution
20
- - Exposes API endpoint `/run/predict` for programmatic access
21
 
22
  ## API Usage
23
 
24
  **Endpoint:**
25
  ```
26
- POST https://huggingface.co/spaces/tofighi/iris-detector/run/predict
27
  ```
28
 
29
  **Request Body Example:**
@@ -49,8 +49,12 @@ POST https://huggingface.co/spaces/tofighi/iris-detector/run/predict
49
  ```python
50
  import requests
51
 
52
- url = "https://huggingface.co/spaces/tofighi/iris-detector/run/predict"
53
  payload = {"data": [5.1, 3.5, 1.4, 0.2]}
54
  resp = requests.post(url, json=payload)
55
  print(resp.json())
56
- ```
 
 
 
 
 
11
 
12
  # ๐ŸŒธ Iris Detector
13
 
14
+ A simple Gradio + FastAPI Space that predicts iris species using a K-Nearest Neighbors classifier (k=5).
15
 
16
  ## Features
17
  - 4 numeric inputs: sepal length, sepal width, petal length, petal width
18
  - Predicts one of 3 classes: `setosa`, `versicolor`, `virginica`
19
  - Shows probability distribution
20
+ - Exposes REST API endpoint `/predict` for programmatic access
21
 
22
  ## API Usage
23
 
24
  **Endpoint:**
25
  ```
26
+ POST https://huggingface.co/spaces/tofighi/iris-detector/predict
27
  ```
28
 
29
  **Request Body Example:**
 
49
  ```python
50
  import requests
51
 
52
+ url = "https://huggingface.co/spaces/tofighi/iris-detector/predict"
53
  payload = {"data": [5.1, 3.5, 1.4, 0.2]}
54
  resp = requests.post(url, json=payload)
55
  print(resp.json())
56
+ ```
57
+
58
+ ## Web Interface
59
+ You can also use the Gradio form in this Space to input iris measurements interactively and get predictions.
60
+
app.py CHANGED
@@ -1,27 +1,43 @@
1
  import gradio as gr
2
  import numpy as np
3
  import joblib
 
 
 
4
 
5
- # Load trained model and target names
6
  model, target_names = joblib.load("iris_knn.pkl")
7
 
8
- def predict(sepal_length, sepal_width, petal_length, petal_width):
9
- """
10
- Predict the iris species given 4 numeric inputs.
 
 
 
 
 
11
 
12
- Returns a dictionary with 'predicted_class' and 'probabilities'.
13
- """
14
- data = np.array([[sepal_length, sepal_width, petal_length, petal_width]])
15
- pred = model.predict(data)[0]
16
- proba = model.predict_proba(data)[0]
 
 
 
17
  return {
18
  "predicted_class": str(target_names[pred]),
19
  "probabilities": {str(target_names[i]): float(proba[i]) for i in range(len(target_names))}
20
  }
21
 
 
 
 
 
 
22
  with gr.Blocks() as demo:
23
  gr.Markdown("# ๐ŸŒธ Iris Detector โ€” KNN Classifier (k=5)")
24
- gr.Markdown("Enter 4 iris flower measurements below to predict the species.")
25
 
26
  with gr.Row():
27
  with gr.Column():
@@ -34,7 +50,7 @@ with gr.Blocks() as demo:
34
  output = gr.JSON(label="Prediction")
35
 
36
  predict_btn.click(
37
- fn=predict,
38
  inputs=[sepal_length, sepal_width, petal_length, petal_width],
39
  outputs=[output]
40
  )
@@ -42,21 +58,21 @@ with gr.Blocks() as demo:
42
  with gr.Column():
43
  gr.Markdown("## ๐Ÿ“– API Usage Guide")
44
  gr.Markdown("""
45
- You can access this model programmatically using the Hugging Face Space API.
46
 
47
  **Endpoint:**
48
  ```
49
- POST https://huggingface.co/spaces/tofighi/iris-detector/run/predict
50
  ```
51
 
52
- **Request Body (JSON):**
53
  ```json
54
  {
55
  "data": [5.1, 3.5, 1.4, 0.2]
56
  }
57
  ```
58
 
59
- **Response:**
60
  ```json
61
  {
62
  "predicted_class": "setosa",
@@ -72,11 +88,11 @@ POST https://huggingface.co/spaces/tofighi/iris-detector/run/predict
72
  ```python
73
  import requests
74
 
75
- url = "https://huggingface.co/spaces/tofighi/iris-detector/run/predict"
76
  payload = {"data": [5.1, 3.5, 1.4, 0.2]}
77
  resp = requests.post(url, json=payload)
78
  print(resp.json())
79
  ```
80
- """)
81
 
82
- demo.launch(share=True)
 
1
  import gradio as gr
2
  import numpy as np
3
  import joblib
4
+ from fastapi import FastAPI
5
+ from pydantic import BaseModel
6
+ from fastapi.middleware.cors import CORSMiddleware
7
 
8
+ # Load trained model
9
  model, target_names = joblib.load("iris_knn.pkl")
10
 
11
+ # --- FastAPI setup ---
12
+ app = FastAPI(title="Iris Detector API")
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
 
20
+ class IrisInput(BaseModel):
21
+ data: list # [sepal_length, sepal_width, petal_length, petal_width]
22
+
23
+ @app.post("/predict")
24
+ def predict_api(input_data: IrisInput):
25
+ arr = np.array([input_data.data])
26
+ pred = model.predict(arr)[0]
27
+ proba = model.predict_proba(arr)[0]
28
  return {
29
  "predicted_class": str(target_names[pred]),
30
  "probabilities": {str(target_names[i]): float(proba[i]) for i in range(len(target_names))}
31
  }
32
 
33
+ # --- Gradio UI setup ---
34
+ def predict_gradio(sepal_length, sepal_width, petal_length, petal_width):
35
+ data = [sepal_length, sepal_width, petal_length, petal_width]
36
+ return predict_api(IrisInput(data=data))
37
+
38
  with gr.Blocks() as demo:
39
  gr.Markdown("# ๐ŸŒธ Iris Detector โ€” KNN Classifier (k=5)")
40
+ gr.Markdown("Enter 4 iris flower measurements below to predict the species. You can also use the REST API.")
41
 
42
  with gr.Row():
43
  with gr.Column():
 
50
  output = gr.JSON(label="Prediction")
51
 
52
  predict_btn.click(
53
+ fn=predict_gradio,
54
  inputs=[sepal_length, sepal_width, petal_length, petal_width],
55
  outputs=[output]
56
  )
 
58
  with gr.Column():
59
  gr.Markdown("## ๐Ÿ“– API Usage Guide")
60
  gr.Markdown("""
61
+ You can access this model programmatically using the REST API.
62
 
63
  **Endpoint:**
64
  ```
65
+ POST https://huggingface.co/spaces/tofighi/iris-detector/predict
66
  ```
67
 
68
+ **Request Body Example:**
69
  ```json
70
  {
71
  "data": [5.1, 3.5, 1.4, 0.2]
72
  }
73
  ```
74
 
75
+ **Response Example:**
76
  ```json
77
  {
78
  "predicted_class": "setosa",
 
88
  ```python
89
  import requests
90
 
91
+ url = "https://huggingface.co/spaces/tofighi/iris-detector/predict"
92
  payload = {"data": [5.1, 3.5, 1.4, 0.2]}
93
  resp = requests.post(url, json=payload)
94
  print(resp.json())
95
  ```
96
+ "")
97
 
98
+ demo.launch(share=True)
requirements.txt CHANGED
@@ -1,4 +1,6 @@
1
- gradio>=3.59.0
2
- scikit-learn
 
3
  numpy
4
- joblib
 
 
1
+ gradio
2
+ fastapi
3
+ uvicorn
4
  numpy
5
+ scikit-learn
6
+ joblib