File size: 7,184 Bytes
87705b0
ea103f3
87705b0
 
 
5e4885c
 
ea103f3
5e4885c
ea103f3
00b43a2
fe32675
ea103f3
fe32675
 
00b43a2
 
 
 
 
ea103f3
4ab1ac8
 
c51dbd9
4ab1ac8
 
 
 
 
ea103f3
4ab1ac8
0c02318
4ab1ac8
 
 
 
00b43a2
ea103f3
 
 
00b43a2
ea103f3
00b43a2
 
 
 
87705b0
ea103f3
5e4885c
 
 
 
 
87705b0
ea103f3
5e4885c
 
 
 
 
 
fe32675
87705b0
 
 
50bf3a0
 
 
 
 
87705b0
50bf3a0
 
 
 
 
87705b0
 
 
 
ea103f3
fe32675
 
 
87705b0
ea103f3
00b43a2
 
5e4885c
 
87705b0
5e4885c
00b43a2
5e4885c
00b43a2
 
 
5e4885c
00b43a2
5e4885c
 
 
 
 
 
 
 
 
ea103f3
dd26f06
 
 
 
29fec18
5e4885c
ea103f3
 
 
 
 
 
 
 
5e4885c
 
 
ea103f3
 
5e4885c
 
 
 
ea103f3
5e4885c
00b43a2
ea103f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
from fastapi import FastAPI, HTTPException
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
from contextlib import asynccontextmanager
import pandas as pd
import time
import json
import os
from datetime import datetime
from pathlib import Path
from huggingface_hub import hf_hub_download

from src.model.model import load_model


class ClientID(BaseModel):
    sk_id_curr: int


def get_features_by_id(sk_id_curr: int) -> pd.DataFrame:
    # CAS TEST (pytest injecte app.state.features)
    if hasattr(app.state, "features") and app.state.features is not None:
        df = app.state.features
    else:
        # CAS LOCAL
        local_path = Path(__file__).resolve().parents[2] / "Data" / "features_clients.csv"
        if local_path.exists():
            df = pd.read_csv(local_path)
        else:
            # CAS HUGGINGFACE
            path = hf_hub_download(
                repo_id="PCelia/credit-scoring-model",
                filename="features_clients.csv",
                token=os.environ.get("HF_TOKEN")
            )
            df = pd.read_csv(path)

    if "SK_ID_CURR" not in df.columns:
        raise KeyError("Dataset invalide")

    row = df[df["SK_ID_CURR"] == sk_id_curr]

    if row.empty:
        raise KeyError("Client not found")

    return row.drop(columns=["SK_ID_CURR"])


def load_features() -> pd.DataFrame:
    # CAS LOCAL
    local_path = Path(__file__).resolve().parents[2] / "Data" / "features_clients.csv"
    if local_path.exists():
        return pd.read_csv(local_path)

    # CAS HUGGINGFACE
    path = hf_hub_download(
        repo_id="PCelia/credit-scoring-model",
        filename="features_clients.csv",
        token=os.environ.get("HF_TOKEN")
    )
    return pd.read_csv(path)

@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.model = load_model()

    # En test (pytest), on ne charge pas les features ici
    if os.environ.get("PYTEST_CURRENT_TEST") is None:
        app.state.features = load_features()

    yield
# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     app.state.model = load_model()
#     app.state.features = load_features()
#     yield


app = FastAPI(lifespan=lifespan)


@app.get("/")
def root():
    return RedirectResponse(url="/docs")


@app.post("/predict_by_id")
def predict_by_id(payload: ClientID):
    start_total = time.perf_counter()

    try:
        start_features = time.perf_counter()
        X = get_features_by_id(payload.sk_id_curr)
        features_time = time.perf_counter() - start_features
    except KeyError:
        raise HTTPException(status_code=404, detail="Client not found")

    start_infer = time.perf_counter()
    score = float(app.state.model.predict_proba(X)[:, 1][0])
    infer_time = time.perf_counter() - start_infer

    total_time = time.perf_counter() - start_total

    print(
        f"features={features_time:.3f}s | "
        f"infer={infer_time:.3f}s | "
        f"total={total_time:.3f}s"
    )

    if not X.empty:
        inputs_dict = X.to_dict(orient="records")[0]
    else:
        inputs_dict = {}

    log_entry = {
        "timestamp": datetime.utcnow().isoformat(),
        "endpoint": "/predict_by_id",
        "sk_id_curr": payload.sk_id_curr,
        "score": score,
        "features_time": features_time,
        "inference_time": infer_time,
        "total_time": total_time,
        "inputs": inputs_dict,
    }

    with open("api_logs.jsonl", "a") as f:
        f.write(json.dumps(log_entry) + "\n")

    return {
        "score": score,
        "features_time": features_time,
        "inference_time": infer_time,
        "total_time": total_time,
    }




# from fastapi import FastAPI, HTTPException
# from pydantic import BaseModel
# from contextlib import asynccontextmanager
# import pandas as pd
# import os
# import time
# import json
# from datetime import datetime
# from huggingface_hub import hf_hub_download
# from src.model.model import load_model

# from fastapi.responses import RedirectResponse



# class ClientID(BaseModel):
#     sk_id_curr: int


# from pathlib import Path
# import os

# def get_features_by_id(sk_id_curr: int) -> pd.DataFrame:
#     # CAS TEST : features injectées par pytest
#     if hasattr(app.state, "features") and app.state.features is not None:
#         df = app.state.features

#     else:
#         # CAS LOCAL
#         local_path = Path(__file__).resolve().parents[2] / "Data" / "features_clients.csv"
#         if local_path.exists():
#             df = pd.read_csv(local_path)

#         else:
#             # CAS HF : repo MODELE
#             path = hf_hub_download(
#                 repo_id="PCelia/credit-scoring-model",
#                 filename="features_clients.csv",
#                 token=os.environ.get("HF_TOKEN")
#             )
#             df = pd.read_csv(path)

#     row = df[df["SK_ID_CURR"] == sk_id_curr]
#     if row.empty:
#         raise KeyError("Client not found")

#     return row.drop(columns=["SK_ID_CURR"])

# def load_features() -> pd.DataFrame:
#     # CAS LOCAL
#     local_path = Path(__file__).resolve().parents[2] / "Data" / "features_clients.csv"
#     if local_path.exists():
#         return pd.read_csv(local_path)

#     # CAS HF
#     path = hf_hub_download(
#         repo_id="PCelia/credit-scoring-model",
#         filename="features_clients.csv",
#         token=os.environ.get("HF_TOKEN")
#     )
#     return pd.read_csv(path)

# @asynccontextmanager
# async def lifespan(app: FastAPI):
#     app.state.model = load_model()

#     # chargement unique des features
#     app.state.features = load_features()

#     yield


# app = FastAPI(lifespan=lifespan)

# @app.get("/")
# def root():
#     return RedirectResponse(url="/docs")

# @app.post("/predict_by_id")
# def predict_by_id(payload: ClientID):
#     start_total = time.perf_counter()

#     try:
#         start_features = time.perf_counter()
#         X = get_features_by_id(payload.sk_id_curr)
#         features_time = time.perf_counter() - start_features
#     except KeyError:
#         raise HTTPException(status_code=404, detail="Client not found")

#     start_infer = time.perf_counter()
#     score = float(app.state.model.predict_proba(X)[:, 1][0])
#     infer_time = time.perf_counter() - start_infer

#     total_time = time.perf_counter() - start_total

#     print(
#         f"features={features_time:.3f}s | "
#         f"infer={infer_time:.3f}s | "
#         f"total={total_time:.3f}s"
#     )
#     inputs_dict = X.to_dict(orient="records")[0]

#     log_entry = {
#     "timestamp": datetime.utcnow().isoformat(),
#     "endpoint": "/predict_by_id",
#     "sk_id_curr": payload.sk_id_curr,
#     "score": score,
#     "features_time": features_time,
#     "inference_time": infer_time,
#     "total_time": total_time,
#     "inputs": inputs_dict
#     }

#     import os
#     print("LOG PATH:", os.path.abspath("api_logs.jsonl"))
#     with open("api_logs.jsonl", "a") as f:
#         f.write(json.dumps(log_entry) + "\n") 
    
#     return {
#         "score": score,
#         "features_time": features_time,
#         "inference_time": infer_time,
#         "total_time": total_time
#     }