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()