File size: 1,641 Bytes
6bdc517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8688e6
 
 
 
6bdc517
 
 
 
 
 
 
 
 
 
 
b8688e6
 
 
 
 
 
 
 
 
 
6bdc517
 
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

import gradio as gr
import pandas as pd
import xgboost as xgb
import json

def train_and_predict(training_json, new_data_json, target_col):
    try:
        # 1. Parse Training Data
        train_data = json.loads(training_json)
        df_train = pd.DataFrame(train_data)
        
        if target_col not in df_train.columns:
            return {"error": f"Target column '{target_col}' not found in training data"}

        # Split into X (Features) and y (Target)
        X_train = df_train.drop(columns=[target_col])
        y_train = df_train[target_col]

        # 2. Train XGBoost (runs on server CPU)
        model = xgb.XGBRegressor()
        model.fit(X_train, y_train)

        # 3. Parse New Data for Prediction
        new_data = json.loads(new_data_json)
        df_new = pd.DataFrame(new_data)
        
        # Ensure columns match training data order
        # (Align columns to handle JSON key scrambling)
        existing_cols = [c for c in X_train.columns if c in df_new.columns]
        df_new = df_new[existing_cols]

        # 4. Predict
        predictions = model.predict(df_new)
        
        # 5. Format Output
        df_new['prediction'] = predictions.astype(float)
        return df_new.to_json(orient='records')

    except Exception as e:
        return json.dumps({"error": str(e)})

# We use Interface to guarantee the '/predict' API name exists
demo = gr.Interface(
    fn=train_and_predict,
    inputs=[
        gr.Textbox(label="Training Data (JSON)"),
        gr.Textbox(label="New Data (JSON)"),
        gr.Textbox(label="Target Column", value="reach")
    ],
    outputs="json"
)

demo.launch()