File size: 3,509 Bytes
b272062
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
from datetime import datetime
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
import seaborn as sns

# Initialize the data
data = []
model = RandomForestClassifier(n_estimators=100)

def train_model(data):
    # Prepare training data from past records
    if len(data) < 10:
        return "Not enough data to train the model"
    
    df = pd.DataFrame(data)
    X = df['card'].apply(lambda x: 0 if x == 'D' else (1 if x == 'T' else 2)).values.reshape(-1, 1)
    y = df['card'].apply(lambda x: 0 if x == 'D' else (1 if x == 'T' else 2))

    model.fit(X, y)
    return "Model trained successfully"

def predict_next_card(data):
    if len(data) < 10:
        return "Not enough data to make a prediction"
    
    df = pd.DataFrame(data)
    X = df['card'].apply(lambda x: 0 if x == 'D' else (1 if x == 'T' else 2)).values.reshape(-1, 1)
    prediction = model.predict(X[-1].reshape(1, -1))

    if prediction == 0:
        return "D"
    elif prediction == 1:
        return "T"
    else:
        return "X"

def generate_card_distribution(data):
    df = pd.DataFrame(data)
    distribution = df['card'].value_counts().sort_index()

    # Create visualization
    plt.figure(figsize=(6, 4))
    sns.barplot(x=distribution.index, y=distribution.values, palette="viridis")
    plt.title('Card Distribution')
    plt.xlabel('Card Type')
    plt.ylabel('Count')
    plt.tight_layout()

    # Save the plot
    plt.savefig('/tmp/card_distribution.png')
    plt.close()
    return '/tmp/card_distribution.png'

def generate_trends_over_time(data):
    df = pd.DataFrame(data)
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    
    # Group by time and count occurrences
    trend_data = df.groupby(df['timestamp'].dt.hour)['card'].value_counts().unstack().fillna(0)

    # Create visualization
    plt.figure(figsize=(10, 6))
    sns.lineplot(data=trend_data, palette="tab10", markers=True)
    plt.title('Trends Over Time')
    plt.xlabel('Hour of Day')
    plt.ylabel('Card Frequency')
    plt.tight_layout()

    # Save the plot
    plt.savefig('/tmp/trends_over_time.png')
    plt.close()
    return '/tmp/trends_over_time.png'

def card_prediction_interface(card_input):
    # Automatically generate timestamp
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Process the input card
    if card_input not in ['D', 'T', 'X']:
        return "Invalid card input. Please enter D, T, or X.", "", "", ""

    # Add the input and timestamp to the dataset
    new_entry = {"card": card_input, "timestamp": timestamp}
    data.append(new_entry)

    # Train the model
    train_status = train_model(data)

    # Predict the next card
    prediction = predict_next_card(data)

    # Generate visualizations
    card_distribution_fig = generate_card_distribution(data)
    trends_fig = generate_trends_over_time(data)

    return prediction, train_status, card_distribution_fig, trends_fig

# Gradio interface
inputs = gr.Textbox(label="Card (D, T, or X)", placeholder="Enter D, T, or X")
outputs = [
    gr.Textbox(label="Prediction"),
    gr.Textbox(label="Training Status"),
    gr.Image(label="Card Distribution"),
    gr.Image(label="Trends Over Time")
]

gr.Interface(
    fn=card_prediction_interface,
    inputs=inputs,
    outputs=outputs,
    title="Enhanced Card Prediction Bot",
    description="An advanced bot that predicts the next card based on historical data and visualizes trends.",
).launch()