GiusMagi commited on
Commit
28a561f
·
verified ·
1 Parent(s): 28c6705

Delete server.py

Browse files
Files changed (1) hide show
  1. server.py +0 -277
server.py DELETED
@@ -1,277 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- import numpy as np
3
- import pandas as pd
4
- import cloudpickle as cp
5
- from fastapi import FastAPI, HTTPException
6
- from fastapi.middleware.cors import CORSMiddleware
7
- from pydantic import BaseModel
8
- import traceback
9
- import logging
10
- import sys
11
- import signal
12
- import threading
13
- import time
14
-
15
- # Setup logging ultra-dettagliato
16
- logging.basicConfig(
17
- level=logging.DEBUG,
18
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
19
- handlers=[logging.StreamHandler(sys.stdout)]
20
- )
21
- logger = logging.getLogger(__name__)
22
-
23
- app = FastAPI(title="Incassi API - Super Debug", version="debug-2.0")
24
-
25
- app.add_middleware(
26
- CORSMiddleware,
27
- allow_origins=["*"],
28
- allow_credentials=True,
29
- allow_methods=["*"],
30
- allow_headers=["*"],
31
- )
32
-
33
- mdl = None
34
-
35
- # Funzione di timeout per debug
36
- def timeout_handler(signum, frame):
37
- logger.error("⏰ TIMEOUT! Operazione bloccata")
38
- raise TimeoutError("Operazione bloccata oltre il timeout")
39
-
40
- def load_model():
41
- global mdl
42
- try:
43
- logger.info("🔧 Caricamento modello...")
44
-
45
- import os
46
- if not os.path.exists("incassi_model.pkl"):
47
- raise FileNotFoundError("File non trovato")
48
-
49
- with open("incassi_model.pkl", "rb") as f:
50
- mdl = cp.load(f)
51
-
52
- logger.info(f"✅ Modello caricato: {type(mdl)}")
53
- logger.info(f"📋 Attributi: {dir(mdl)[:10]}...") # primi 10 attributi
54
-
55
- return True
56
- except Exception as e:
57
- logger.error(f"❌ Errore caricamento: {e}")
58
- return False
59
-
60
- model_loaded = load_model()
61
-
62
- class PredictIn(BaseModel):
63
- Debitore_cluster: str | None = None
64
- Stato_Giudizio: str | None = None
65
- Cedente: str | None = None
66
- Importo_iniziale_outstanding: float | None = None
67
- Decreto_sospeso: str | None = None
68
- Notifica_Decreto: str | None = None
69
- Opposizione_al_decreto_ingiuntivo: str | None = None
70
- Ricorso_al_TAR: str | None = None
71
- Sentenza_TAR: str | None = None
72
- Atto_di_Precetto: str | None = None
73
- Decreto_Ingiuntivo: str | None = None
74
- Sentenza_giudizio_opposizione: str | None = None
75
- giorni_da_iscrizione: int | None = None
76
- giorni_da_cessione: int | None = None
77
- Zona: str | None = None
78
-
79
- def safe_to_model_format(d: dict) -> pd.DataFrame:
80
- """Conversione sicura con timeout"""
81
- logger.info("🔄 Conversione input...")
82
-
83
- row = {
84
- "Debitore_cluster": d.get("Debitore_cluster"),
85
- "Stato_Giudizio": d.get("Stato_Giudizio"),
86
- "Cedente": d.get("Cedente"),
87
- "Importo iniziale outstanding": d.get("Importo_iniziale_outstanding"),
88
- "Decreto sospeso": d.get("Decreto_sospeso"),
89
- "Notifica Decreto": d.get("Notifica_Decreto"),
90
- "Opposizione al decreto ingiuntivo": d.get("Opposizione_al_decreto_ingiuntivo"),
91
- "Ricorso al TAR": d.get("Ricorso_al_TAR"),
92
- "Sentenza TAR": d.get("Sentenza_TAR"),
93
- "Atto di Precetto": d.get("Atto_di_Precetto"),
94
- "Decreto Ingiuntivo": d.get("Decreto_Ingiuntivo"),
95
- "Sentenza giudizio opposizione": d.get("Sentenza_giudizio_opposizione"),
96
- "giorni_da_iscrizione": d.get("giorni_da_iscrizione"),
97
- "giorni_da_cessione": d.get("giorni_da_cessione"),
98
- "Zona": d.get("Zona"),
99
- }
100
-
101
- df = pd.DataFrame([row])
102
- logger.info(f"✅ DataFrame: {df.shape}, cols: {list(df.columns)[:5]}...")
103
- return df
104
-
105
- @app.get("/")
106
- def root():
107
- return {
108
- "ok": True,
109
- "service": "incassi-super-debug",
110
- "model_loaded": model_loaded,
111
- }
112
-
113
- @app.get("/status")
114
- def status():
115
- if not mdl:
116
- return {"error": "Modello non caricato"}
117
-
118
- return {
119
- "model_loaded": True,
120
- "model_type": str(type(mdl)),
121
- "has_predict": hasattr(mdl, "predict"),
122
- "has_stage1": hasattr(mdl, "stage1"),
123
- "has_stage2": hasattr(mdl, "stage2"),
124
- "methods": [m for m in dir(mdl) if not m.startswith('_')][:10]
125
- }
126
-
127
- @app.post("/test_conversion")
128
- def test_conversion(inp: PredictIn):
129
- """Test solo conversione dati"""
130
- try:
131
- logger.info("🧪 Test conversione...")
132
-
133
- if not mdl:
134
- raise HTTPException(status_code=503, detail="Modello non caricato")
135
-
136
- # Solo conversione
137
- df = safe_to_model_format(inp.dict())
138
- logger.info("✅ Conversione OK")
139
-
140
- return {
141
- "status": "conversion_ok",
142
- "shape": df.shape,
143
- "columns_sample": list(df.columns)[:10],
144
- "first_row_sample": {k: str(v)[:50] for k, v in df.iloc[0].to_dict().items() if k in list(df.columns)[:5]}
145
- }
146
-
147
- except Exception as e:
148
- logger.error(f"❌ Errore conversione: {e}")
149
- logger.error(f"❌ Traceback:\n{traceback.format_exc()}")
150
- raise HTTPException(status_code=500, detail=f"Errore conversione: {str(e)}")
151
-
152
- @app.post("/test_ensure_cols")
153
- def test_ensure_cols(inp: PredictIn):
154
- """Test solo _ensure_raw_cols"""
155
- try:
156
- logger.info("🧪 Test ensure_raw_cols...")
157
-
158
- if not mdl:
159
- raise HTTPException(status_code=503, detail="Modello non caricato")
160
-
161
- df = safe_to_model_format(inp.dict())
162
- logger.info("🔧 Chiamata _ensure_raw_cols...")
163
-
164
- # Test con timeout di 10 secondi
165
- def run_ensure():
166
- return mdl._ensure_raw_cols(df)
167
-
168
- # Esegui in thread separato per timeout
169
- import concurrent.futures
170
- with concurrent.futures.ThreadPoolExecutor() as executor:
171
- future = executor.submit(run_ensure)
172
- try:
173
- df_ensured = future.result(timeout=10)
174
- logger.info("✅ _ensure_raw_cols OK")
175
- return {
176
- "status": "ensure_cols_ok",
177
- "original_shape": df.shape,
178
- "ensured_shape": df_ensured.shape
179
- }
180
- except concurrent.futures.TimeoutError:
181
- logger.error("⏰ _ensure_raw_cols TIMEOUT")
182
- raise HTTPException(status_code=408, detail="_ensure_raw_cols timeout")
183
-
184
- except HTTPException:
185
- raise
186
- except Exception as e:
187
- logger.error(f"❌ Errore ensure_cols: {e}")
188
- logger.error(f"❌ Traceback:\n{traceback.format_exc()}")
189
- raise HTTPException(status_code=500, detail=f"Errore ensure_cols: {str(e)}")
190
-
191
- @app.post("/test_preprocess")
192
- def test_preprocess(inp: PredictIn):
193
- """Test solo _preprocess_apply"""
194
- try:
195
- logger.info("🧪 Test preprocess...")
196
-
197
- if not mdl:
198
- raise HTTPException(status_code=503, detail="Modello non caricato")
199
-
200
- df = safe_to_model_format(inp.dict())
201
- df_ensured = mdl._ensure_raw_cols(df)
202
-
203
- logger.info("🔧 Chiamata _preprocess_apply...")
204
-
205
- # Test con timeout
206
- def run_preprocess():
207
- return mdl._preprocess_apply(df_ensured)
208
-
209
- import concurrent.futures
210
- with concurrent.futures.ThreadPoolExecutor() as executor:
211
- future = executor.submit(run_preprocess)
212
- try:
213
- df_processed = future.result(timeout=15)
214
- logger.info("✅ _preprocess_apply OK")
215
- return {
216
- "status": "preprocess_ok",
217
- "processed_shape": df_processed.shape,
218
- "processed_columns_count": len(df_processed.columns)
219
- }
220
- except concurrent.futures.TimeoutError:
221
- logger.error("⏰ _preprocess_apply TIMEOUT")
222
- raise HTTPException(status_code=408, detail="_preprocess_apply timeout")
223
-
224
- except HTTPException:
225
- raise
226
- except Exception as e:
227
- logger.error(f"❌ Errore preprocess: {e}")
228
- logger.error(f"❌ Traceback:\n{traceback.format_exc()}")
229
- raise HTTPException(status_code=500, detail=f"Errore preprocess: {str(e)}")
230
-
231
- @app.post("/predict")
232
- def predict(inp: PredictIn):
233
- """Predizione completa con timeout estremo"""
234
- try:
235
- logger.info("🚀 PREDICT con timeout...")
236
-
237
- if not mdl:
238
- raise HTTPException(status_code=503, detail="Modello non caricato")
239
-
240
- df = safe_to_model_format(inp.dict())
241
-
242
- # Predict con timeout di 30 secondi
243
- def run_predict():
244
- logger.info("🔧 Esecuzione mdl.predict()...")
245
- result = mdl.predict(df)
246
- logger.info("✅ mdl.predict() completato")
247
- return result
248
-
249
- import concurrent.futures
250
- with concurrent.futures.ThreadPoolExecutor() as executor:
251
- future = executor.submit(run_predict)
252
- try:
253
- result = future.result(timeout=30)
254
-
255
- p100, prob_ord, yhat, final_class, _ = result
256
- response = {
257
- "p100": float(p100),
258
- "prob_ord": np.asarray(prob_ord, dtype=float).tolist(),
259
- "yhat": float(yhat),
260
- "final_class": str(final_class),
261
- }
262
-
263
- logger.info(f"✅ Predizione completata: {response['yhat']:.2f}")
264
- return response
265
-
266
- except concurrent.futures.TimeoutError:
267
- logger.error("⏰ PREDICT TIMEOUT dopo 30 secondi")
268
- raise HTTPException(status_code=408, detail="Predizione timeout - modello bloccato")
269
-
270
- except HTTPException:
271
- raise
272
- except Exception as e:
273
- logger.error(f"❌ ERRORE PREDICT: {e}")
274
- logger.error(f"❌ Traceback:\n{traceback.format_exc()}")
275
- raise HTTPException(status_code=500, detail=f"Errore predict: {str(e)}")
276
-
277
- logger.info("🚀 Super Debug Server inizializzato")