AntOG96 commited on
Commit
173ba95
·
0 Parent(s):

Initial commit

Browse files
Files changed (11) hide show
  1. Dockerfile +16 -0
  2. README.md +12 -0
  3. app.py +222 -0
  4. export_trained_model.py +12 -0
  5. model.ipynb +0 -0
  6. model/MLmodel +37 -0
  7. model/conda.yaml +14 -0
  8. model/python_env.yaml +7 -0
  9. model/requirements.txt +7 -0
  10. requirements.txt +12 -0
  11. test.py +102 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9.0
2
+
3
+ WORKDIR /home/app
4
+
5
+ RUN apt-get update -y
6
+ RUN apt-get install nano unzip
7
+ RUN apt install curl -y
8
+
9
+ RUN curl -fsSL https://get.deta.dev/cli.sh | sh
10
+
11
+ COPY requirements.txt /dependencies/requirements.txt
12
+ RUN pip install -r /dependencies/requirements.txt
13
+
14
+ COPY . /home/app
15
+
16
+ CMD gunicorn app:app --bind 0.0.0.0:$PORT --worker-class uvicorn.workers.UvicornWorker
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Getaround Api
3
+ emoji: 🌍
4
+ colorFrom: gray
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ license: apache-2.0
9
+ short_description: GetAround API
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mlflow
2
+ import uvicorn
3
+ import
4
+ import json
5
+ import pandas as pd
6
+ from pydantic import BaseModel
7
+ from typing import Literal, List, Union
8
+ from fastapi import FastAPI, File, UploadFile
9
+
10
+ description = """
11
+ The GetAround API helps car owners optimize rental pricing through intelligent predictions,
12
+ while also providing insights to better understand their vehicles and make informed decisions.
13
+
14
+ ## Preview
15
+
16
+ Where you can:
17
+ * `/preview` a few rows of your dataset
18
+ * get `/unique-values` of a given column in your dataset
19
+
20
+ ## Categorical
21
+
22
+ Where you can:
23
+ * `/groupby` a given column and chose an aggregation metric
24
+ * `/filter-by` one of several categories within your dataset
25
+
26
+ ## Predictions
27
+
28
+ Where you can:
29
+ * `/predict` the optimum price for a car
30
+ * `/batch-predict` where you can upload a file to get predictions for several cars
31
+
32
+
33
+ Check out documentation for more information on each endpoint.
34
+ """
35
+
36
+ tags_metadata = [
37
+ {
38
+ "name": "Categorical",
39
+ "description": "Endpoints that deal with categorical data",
40
+ },
41
+ {"name": "Preview", "description": "Endpoints that quickly explore dataset"},
42
+ {
43
+ "name": "Predictions",
44
+ "description": "Endpoints that uses our Machine Learning model for pricing optimization",
45
+ },
46
+ ]
47
+
48
+ app = FastAPI(
49
+ title="🚙 GETAROUND API",
50
+ description=description,
51
+ version="0.1",
52
+ contact={
53
+ "name": "GETAROUND API - by Antoine OGER"
54
+ },
55
+ openapi_tags=tags_metadata,
56
+ )
57
+
58
+
59
+ class GroupBy(BaseModel):
60
+ column: str
61
+ by_method: Literal["mean", "median", "max", "min", "sum", "count"] = "mean"
62
+
63
+
64
+ class FilterBy(BaseModel):
65
+ column: str
66
+ by_category: List[str] = None
67
+
68
+
69
+ class PredictionFeatures(BaseModel):
70
+ model_key: str
71
+ mileage: Union[int, float]
72
+ engine_power: Union[int, float]
73
+ fuel: str
74
+ paint_color: str
75
+ car_type: str
76
+ private_parking_available: bool
77
+ has_gps: bool
78
+ has_air_conditioning: bool
79
+ automatic_car : bool
80
+ has_getaround_connect: bool
81
+ has_speed_regulator: bool
82
+ winter_tires: bool
83
+
84
+
85
+ @app.get("/", tags=["Introduction Endpoints"])
86
+ async def index():
87
+ """
88
+ Simply returns a welcome message!
89
+ """
90
+ message = "Hello world! This `/` is the most simple and default endpoint. If you want to learn more, check out documentation of the api at `/docs` or first check `/preview`"
91
+ return message
92
+
93
+
94
+ @app.get("/preview", tags=["Preview"])
95
+ async def preview(rows: int = 10):
96
+ """
97
+ Get a sample of your whole dataset.
98
+ You can specify how many rows you want by specifying a value for `rows`, default is `10`
99
+ """
100
+ df = pd.read_csv("https://full-stack-assets.s3.eu-west-3.amazonaws.com/Deployment/get_around_pricing_project.csv", index_col=0)
101
+ sample = df.sample(rows)
102
+ return sample.to_dict(orient="records")
103
+
104
+
105
+ @app.get("/unique-values", tags=["Preview"])
106
+ async def unique_values(column: str):
107
+ """
108
+ Get unique values from a given column
109
+ """
110
+ df = pd.read_csv("https://full-stack-assets.s3.eu-west-3.amazonaws.com/Deployment/get_around_pricing_project.csv", index_col=0)
111
+ unique_vals = df[column].dropna().unique().tolist()
112
+
113
+ return unique_vals
114
+
115
+
116
+ @app.post("/groupby", tags=["Categorical"])
117
+ async def group_by(groupBy: GroupBy):
118
+ """
119
+ Get data grouped by a given column. Accepted columns are:
120
+
121
+ * `["model_key","fuel", "paint_color", "car_type"]`
122
+
123
+ You can use different method to group by category which are:
124
+
125
+ * `mean`
126
+ * `median`
127
+ * `min`
128
+ * `max`
129
+ * `sum`
130
+ * `count`
131
+ """
132
+
133
+ df = pd.read_csv("https://full-stack-assets.s3.eu-west-3.amazonaws.com/Deployment/get_around_pricing_project.csv", index_col=0)
134
+
135
+ method = groupBy.by_method
136
+
137
+ # Ne garder que les colonnes numériques pour l'agrégation
138
+ numeric_cols = df.select_dtypes(include=["float", "int"]).columns
139
+
140
+
141
+ if method == "mean":
142
+ df = df.groupby(groupBy.column)[numeric_cols].mean()
143
+ if method == "median":
144
+ df = df.groupby(groupBy.column)[numeric_cols].median()
145
+ if method == "min":
146
+ df = df.groupby(groupBy.column)[numeric_cols].min()
147
+ if method == "max":
148
+ df = df.groupby(groupBy.column)[numeric_cols].max()
149
+ if method == "sum":
150
+ df = df.groupby(groupBy.column)[numeric_cols].sum()
151
+ if method == "count":
152
+ df = df.groupby(groupBy.column)[numeric_cols].count()
153
+
154
+ df = df.reset_index()
155
+ return df.to_dict(orient="records")
156
+
157
+
158
+ @app.post("/filter-by", tags=["Categorical"])
159
+ async def filter_by(filterBy: FilterBy):
160
+ """
161
+ Filter by one or more categories in a given column. Columns possible values are:
162
+
163
+ * `["model_key","fuel", "paint_color", "car_type"]`
164
+
165
+ Check values within dataset to know what kind of `categories` you can filter by. You can use `/unique-values` path to check them out.
166
+ `categories` must be `list` format.
167
+ """
168
+
169
+ df = pd.read_csv("https://full-stack-assets.s3.eu-west-3.amazonaws.com/Deployment/get_around_pricing_project.csv", index_col=0)
170
+
171
+ if filterBy.by_category != None:
172
+ df = df[df[filterBy.column].isin(filterBy.by_category)]
173
+ df = df.reset_index()
174
+ return df.to_dict(orient="records")
175
+ else:
176
+ msg = "Please chose a column to filter by"
177
+ return msg
178
+
179
+
180
+ @app.post("/predict", tags=["Predictions"])
181
+ async def predict(predictionFeatures: PredictionFeatures):
182
+ """
183
+ Prediction for one observation. Endpoint will return a dictionnary like this:
184
+
185
+ ```
186
+ {'prediction': PREDICTION_VALUE}
187
+ ```
188
+
189
+ You need to give this endpoint all columns values as dictionnary, or form data.
190
+ """
191
+ # Read data
192
+ df = pd.DataFrame([predictionFeatures.dict()])
193
+
194
+ # Load model as a PyFuncModel.
195
+ loaded_model = mlflow.pyfunc.load_model("model")
196
+
197
+ # prediction = loaded_model.predict(df)
198
+ prediction = loaded_model.predict(pd.DataFrame(df))
199
+
200
+ # Format response
201
+ response = {"prediction": prediction.tolist()[0]}
202
+ return response
203
+
204
+
205
+ @app.post("/batch-predict", tags=["Predictions"])
206
+ async def batch_predict(file: UploadFile = File(...)):
207
+ """
208
+ Make prediction on a batch of observation. This endpoint accepts only **csv files** containing
209
+ all the trained columns WITHOUT the target variable.
210
+ """
211
+ # Read file
212
+ df = pd.read_csv(file.file)
213
+
214
+ # Load model as a PyFuncModel.
215
+ loaded_model = mlflow.pyfunc.load_model("model")
216
+ predictions = loaded_model.predict(pd.DataFrame(df))
217
+
218
+ return predictions.tolist()
219
+
220
+
221
+ if __name__ == "__main__":
222
+ uvicorn.run(app, host="0.0.0.0", port=4000, debug=True, reload=True)
export_trained_model.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+
3
+ # Chemin complet du modèle que tu veux exporter
4
+ source_path = "mlruns/181198585705168272/models/m-ad163c4e6fa94a90ad9d38f10f938577/artifacts"
5
+
6
+ # Destination où tu veux sauvegarder le modèle “en dur”
7
+ destination_path = "./exported_model"
8
+
9
+ # Copie tout le dossier
10
+ shutil.copytree(source_path, destination_path, dirs_exist_ok=True)
11
+
12
+ print(f"✅ Modèle exporté en dur dans {destination_path}")
model.ipynb ADDED
File without changes
model/MLmodel ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ artifact_path: file:///home/app/mlruns/181198585705168272/models/m-ad163c4e6fa94a90ad9d38f10f938577/artifacts
2
+ flavors:
3
+ python_function:
4
+ env:
5
+ conda: conda.yaml
6
+ virtualenv: python_env.yaml
7
+ loader_module: mlflow.sklearn
8
+ model_path: model.pkl
9
+ predict_fn: predict
10
+ python_version: 3.9.25
11
+ sklearn:
12
+ code: null
13
+ pickled_model: model.pkl
14
+ serialization_format: cloudpickle
15
+ sklearn_version: 1.6.1
16
+ is_signature_from_type_hint: false
17
+ mlflow_version: 3.1.4
18
+ model_id: m-ad163c4e6fa94a90ad9d38f10f938577
19
+ model_size_bytes: 3567007
20
+ model_uuid: m-ad163c4e6fa94a90ad9d38f10f938577
21
+ prompts: null
22
+ run_id: 487e8152348b42beb0405ba482f237a2
23
+ signature:
24
+ inputs: '[{"type": "string", "name": "model_key", "required": true}, {"type": "long",
25
+ "name": "mileage", "required": true}, {"type": "long", "name": "engine_power",
26
+ "required": true}, {"type": "string", "name": "fuel", "required": true}, {"type":
27
+ "string", "name": "paint_color", "required": true}, {"type": "string", "name":
28
+ "car_type", "required": true}, {"type": "boolean", "name": "private_parking_available",
29
+ "required": true}, {"type": "boolean", "name": "has_gps", "required": true}, {"type":
30
+ "boolean", "name": "has_air_conditioning", "required": true}, {"type": "boolean",
31
+ "name": "automatic_car", "required": true}, {"type": "boolean", "name": "has_getaround_connect",
32
+ "required": true}, {"type": "boolean", "name": "has_speed_regulator", "required":
33
+ true}, {"type": "boolean", "name": "winter_tires", "required": true}]'
34
+ outputs: '[{"type": "tensor", "tensor-spec": {"dtype": "float64", "shape": [-1]}}]'
35
+ params: null
36
+ type_hint_from_example: false
37
+ utc_time_created: '2026-01-15 23:53:30.330167'
model/conda.yaml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ channels:
2
+ - conda-forge
3
+ dependencies:
4
+ - python=3.9.25
5
+ - pip<=23.0.1
6
+ - pip:
7
+ - mlflow==3.1.4
8
+ - cloudpickle==3.1.2
9
+ - numpy==2.0.2
10
+ - pandas==2.3.3
11
+ - psutil==7.2.1
12
+ - scikit-learn==1.6.1
13
+ - scipy==1.13.1
14
+ name: mlflow-env
model/python_env.yaml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ python: 3.9.25
2
+ build_dependencies:
3
+ - pip==23.0.1
4
+ - setuptools==79.0.1
5
+ - wheel==0.45.1
6
+ dependencies:
7
+ - -r requirements.txt
model/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ mlflow==3.1.4
2
+ cloudpickle==3.1.2
3
+ numpy==2.0.2
4
+ pandas==2.3.3
5
+ psutil==7.2.1
6
+ scikit-learn==1.6.1
7
+ scipy==1.13.1
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.100.0
2
+ uvicorn[standard]
3
+ pydantic<2.0
4
+ typing
5
+ pandas
6
+ gunicorn
7
+ openpyxl
8
+ mlflow
9
+ boto3
10
+ scikit-learn
11
+ python-multipart
12
+ psutil==7.0.0
test.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import pandas as pd
4
+
5
+
6
+ ### Test preview endpoint
7
+ def test_preview():
8
+ print("###test_preview###")
9
+
10
+ r = requests.get("")
11
+
12
+ response = r.json()
13
+ print(pd.DataFrame(response))
14
+
15
+ test_preview()
16
+
17
+
18
+ ### Test uniquevalues endpoint
19
+ def test_uniquevalues():
20
+ print("###test_uniquevalues###")
21
+
22
+ payload = {"column": "model_key"}
23
+ r = requests.get("", params=payload)
24
+
25
+ response = r.json()
26
+ print(response)
27
+
28
+ test_uniquevalues()
29
+
30
+
31
+ ### Test groupby endpoint
32
+ def test_groupby():
33
+ print("###test_groupby###")
34
+
35
+ payload = {"column": "model_key", "by_method": "mean"}
36
+ r = requests.post("", json=payload)
37
+
38
+ response = r.json()
39
+ print(pd.DataFrame(response))
40
+
41
+ test_groupby()
42
+
43
+
44
+ ### Test filter-by endpoint
45
+ def test_filterBy():
46
+ print("###test_filterBy###")
47
+
48
+ payload = {
49
+ "column": "paint_color",
50
+ "by_category": ["black", "grey"],
51
+ }
52
+
53
+ r = requests.post("", json=payload)
54
+
55
+ response = r.json()
56
+ print(pd.DataFrame(response))
57
+
58
+ test_filterBy()
59
+
60
+
61
+ #### Test ML Model
62
+ def test_prediction():
63
+ print("###test_prediction###")
64
+
65
+ payload = {
66
+ "model_key": "Peugeot",
67
+ "mileage": 139000,
68
+ "engine_power": 135,
69
+ "fuel": "diesel",
70
+ "paint_color": "blue",
71
+ "car_type": "convertible",
72
+ "private_parking_available": True,
73
+ "has_gps": True,
74
+ "has_air_conditioning": True,
75
+ "automatic_car": True,
76
+ "has_getaround_connect": True,
77
+ "has_speed_regulator": True,
78
+ "winter_tires": True
79
+ }
80
+
81
+ r = requests.post("", json=payload)
82
+
83
+ response = r.json()
84
+ print(round(response["prediction"], 2))
85
+
86
+ test_prediction()
87
+
88
+
89
+ #### Test batch pred
90
+ def test_batch():
91
+ print("###test_batchprediction###")
92
+
93
+ df = pd.read_csv("https://full-stack-assets.s3.eu-west-3.amazonaws.com/Deployment/get_around_pricing_project.csv", index_col=0)
94
+
95
+ df = df.iloc[:, :-1]
96
+ myfile = df.to_csv(index=False)
97
+ r = requests.post("", files={"file": myfile})
98
+
99
+ response = r.json()
100
+ print(pd.DataFrame(response))
101
+
102
+ test_batch()