File size: 7,944 Bytes
b8ca8ad
79a6a3c
99ee88a
c7cc1b5
 
a9a2a30
 
767ab92
c7cc1b5
6fadde3
 
 
 
 
 
 
 
c7cc1b5
a9a2a30
 
79a6a3c
767ab92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79a6a3c
 
 
abf024a
 
 
c7cc1b5
 
8c90b73
c7cc1b5
8c90b73
 
13ba4b4
 
8c90b73
13ba4b4
 
8c90b73
c7cc1b5
8c90b73
 
 
 
 
 
 
 
 
 
 
 
 
 
c7cc1b5
8c90b73
 
 
 
 
 
 
 
13ba4b4
8c90b73
 
13ba4b4
8c90b73
13ba4b4
8c90b73
 
 
 
c341bcb
8c90b73
 
c7cc1b5
8c90b73
 
 
 
 
 
 
 
c7cc1b5
8c90b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c341bcb
8c90b73
 
 
 
 
 
 
c341bcb
8c90b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c341bcb
8c90b73
 
 
 
c7cc1b5
 
8c90b73
 
 
 
 
c7cc1b5
 
8c90b73
c341bcb
13ba4b4
8c90b73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
from fastapi import FastAPI
from controller import Controller
from database import Database
import logging
import warnings
from sklearn.exceptions import InconsistentVersionWarning
from contextlib import asynccontextmanager

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout)
    ]
)

logger = logging.getLogger(__name__)
warnings.filterwarnings('ignore', category=InconsistentVersionWarning)
logging.getLogger('absl').setLevel(logging.ERROR)

@asynccontextmanager
async def lifespan(app: FastAPI):
    global controller
    try:
        logger.info("Initializing Controller and Models on startup...")
        controller = Controller(database_sensor={})
        logger.info("Controller and Models loaded successfully!")
    except Exception as e:
        logger.critical(f"Failed to initialize Controller on startup: {str(e)}")
        raise
    yield
    logger.info("Shutting down application...")

app = FastAPI(lifespan=lifespan)
database = Database()
controller: Controller | None = None
        
@app.get("/")
def greet_json():
    return {"Hello": "World!"}

@app.get("/predict-machine")
def predict_machine():
    logger.info("Prediction request received")
    
    machine_ids = database.get_all_machine_id()
    
    if not machine_ids or not hasattr(machine_ids, 'data') or not machine_ids.data:
        logger.warning("No machines found in database")
        return {
            "success": False,
            "error": "No machines found in database"
        }
    
    all_results = []
    
    for machine in machine_ids.data:  
        machine_id = machine.get('id')
        machine_name = machine.get('name')
        sensor = database.get_sensor_readings(1, machine_id)

        # Check if sensor is a duplicate error response
        if isinstance(sensor, dict) and sensor.get("message") == "Data already predicted":
            logger.warning("Data already predicted - returning error")
            all_results.append({
                "machine_name": machine_name,
                "success": False,
                "error": "Data already predicted"
            })
            continue
    
        if sensor is None:
            logger.warning("No sensor data available")
            all_results.append({
                "machine_name": machine_name,
                "success": False,
                "error": "No sensor data available"
            })
            continue
        
        sensor_udi = sensor.get("udi")
        logger.debug(f"Processing sensor data for : {machine_name}, UDI: {sensor_udi}")
        
        controller.set_sensor_data(sensor)
        
        binary_result = controller.predict_binary()
        if not binary_result.get("success"):
            logger.error(f"Binary prediction failed for {machine_name}: {binary_result.get('error')}")
            if binary_result.get("error") != "Data already predicted":
                database.reset_last_processed_id(machine_id)
            all_results.append(binary_result)
            continue
        
        if binary_result.get("failure_predicted"):
            logger.info("Failure predicted - running classification and time series analysis")
            classification_result = controller.predict_classification()
            
            sensor_lstm = database.get_sensor_readings(30, machine_id=machine_id)
            if sensor_lstm is None or (isinstance(sensor_lstm, dict) and sensor_lstm.get("message")):
                logger.warning(f"Not enough time-series data available for {machine_name}")
                sensor_lstm = []
            
            # Set time series data for RUL prediction
            if sensor_lstm:
                controller.set_sensor_data(sensor_lstm)
            else:
                controller.set_sensor_data(sensor)
            
            time_series_result = controller.predict_time_series()
            
            if classification_result.get("success") and time_series_result.get("success"):
                logger.info(f"Prediction successful for {machine_name}- failure_type: {classification_result.get('failure_type')}")

                save_result = database.update_or_create_new_predictions(
                    machine_id=sensor.get("machine_id"),
                    timestamp=sensor.get("timestamp"),
                    risk_score=classification_result.get("risk_score"),
                    failure_predicted=True,
                    failure_type=classification_result.get("failure_type"),
                    predicted_failure_time=time_series_result.get("predictions", {}).get("predicted_failure_date"),
                    confidence=classification_result.get("confidence")
                )
                
                if save_result is None or save_result.get("error"):
                    logger.error(f"Failed to save prediction for UDI {sensor_udi} - resetting for retry")
                    database.reset_last_processed_id(machine_id)
                    all_results.append({
                        "machine_name": machine_name,
                        "success": False,
                        "error": "Failed to save prediction to database"
                    })
                    continue
                logger.info(f"Prediction successfully saved for UDI {sensor_udi}")
                database.mark_as_processed(machine_id, sensor_udi)
                
                all_results.append({
                    "machine_name": machine_name,
                    "success": True,
                    "failure_predicted": True,
                    "failure_type": classification_result.get("failure_type"),
                    "confidence": classification_result.get("confidence"),
                    "risk_score": classification_result.get("risk_score"),
                    "risk_level": classification_result.get("risk_level"),
                    "all_probabilities": classification_result.get("all_probabilities"),
                    "rul_prediction": time_series_result.get("predictions"),
                    "timestamp": sensor.get("timestamp"),
                    "save_data": save_result
                })
            else:
                logger.error(f"Classification or time series prediction failed for UDI {sensor_udi}")
                if not (isinstance(classification_result, dict) and classification_result.get("error") == "Data already predicted"):
                    database.reset_last_processed_id(machine_id)
                all_results.append(binary_result)
        else:
            logger.info(f"No failure predicted for UDI {sensor_udi}")
            save_result = database.update_or_create_new_predictions(
                machine_id=sensor.get("machine_id"),
                timestamp=sensor.get("timestamp"),
                risk_score=binary_result.get("risk_score"),
                failure_predicted=binary_result.get("failure_predicted"),
                failure_type=None,
                predicted_failure_time=None,
                confidence=binary_result.get("confidence")
            )
            
            if save_result and save_result.get("success"):
                database.mark_as_processed(machine_id, sensor_udi)
            
            all_results.append({
                "machine_name": machine_name,
                "success": binary_result.get("success"),
                "failure_predicted": binary_result.get("failure_predicted"),
                "risk_score": binary_result.get("risk_score"),
                "confidence": binary_result.get("confidence"),
                "timestamp": sensor.get("timestamp"),
                "save_data": save_result
            })
    return {
        "success": True,
        "machines_processed": len([r for r in all_results if r.get("success")]),
        "total_machines": len(all_results),
        "results": all_results
    }