| import gradio as gr |
| import numpy as np |
| import pandas as pd |
| import os |
| import datetime |
| import matplotlib |
| matplotlib.use('Agg') |
| import matplotlib.pyplot as plt |
| from sklearn.datasets import make_classification |
| from sklearn.neighbors import KNeighborsClassifier |
| from sklearn.ensemble import RandomForestClassifier |
| from sklearn.neural_network import MLPClassifier |
| from sklearn.model_selection import train_test_split |
| from sklearn.metrics import accuracy_score |
|
|
| plt.style.use('dark_background') |
|
|
| |
| DATA_DIR = "/data" |
| if not os.path.exists(DATA_DIR): |
| DATA_DIR = "." |
| DB_FILE = os.path.join(DATA_DIR, "galactic_leaderboard.csv") |
|
|
| def load_leaderboard(): |
| if os.path.exists(DB_FILE): |
| df = pd.read_csv(DB_FILE) |
| |
| |
| |
| |
| df = df.sort_values(by=["Score", "Power Draw", "Timestamp"], ascending=[False, True, True]).reset_index(drop=True) |
| df.insert(0, "Rank", range(1, len(df) + 1)) |
| |
| df["Score"] = df["Score"].apply(lambda x: f"{x:.2f}%") |
| return df |
| return pd.DataFrame(columns=["Rank", "Commander Name", "Score", "Power Draw", "Grade", "Timestamp"]) |
|
|
| def get_grade(score): |
| if score >= 90.0: return "๐ S-Tier" |
| if score >= 85.0: return "๐ฅ A-Tier" |
| if score >= 75.0: return "๐ฅ B-Tier" |
| if score >= 65.0: return "๐ฅ C-Tier" |
| return "๐ F-Tier" |
|
|
| def submit_score(name, score_text, power_text, grade_text): |
| if not name.strip() or score_text == "0.00%": |
| return "โ ๏ธ Awaiting valid targeting data!", load_leaderboard() |
| |
| commander = name.strip() |
| score_val = float(score_text.replace('%', '')) |
| power_val = int(power_text) |
| timestamp = datetime.datetime.now().strftime("%H:%M:%S") |
|
|
| if os.path.exists(DB_FILE): |
| df = pd.read_csv(DB_FILE) |
| else: |
| df = pd.DataFrame(columns=["Commander Name", "Score", "Power Draw", "Grade", "Timestamp"]) |
| |
| if commander in df["Commander Name"].values: |
| idx = df.index[df["Commander Name"] == commander].tolist()[0] |
| current_best_score = float(df.at[idx, "Score"]) |
| current_best_power = int(df.at[idx, "Power Draw"]) |
| |
| should_update = False |
| msg = "" |
| |
| |
| if score_val > current_best_score: |
| should_update = True |
| msg = f"๐ฅ NEW PERSONAL BEST! Score improved to {score_val}%." |
| |
| elif score_val == current_best_score and power_val < current_best_power: |
| should_update = True |
| msg = f"โก EFFICIENCY UPGRADE! Same score, but lower Power Draw." |
| else: |
| msg = f"๐ Your previous system ({current_best_score}% at {current_best_power} Power) is still superior." |
| |
| if should_update: |
| df.loc[idx, ["Score", "Power Draw", "Grade", "Timestamp"]] = [score_val, power_val, grade_text, timestamp] |
| else: |
| new_entry = pd.DataFrame([{ |
| "Commander Name": commander, "Score": score_val, |
| "Power Draw": power_val, "Grade": grade_text, "Timestamp": timestamp |
| }]) |
| df = pd.concat([df, new_entry], ignore_index=True) |
| msg = "โ
Commander registered to the Galactic Leaderboard." |
| |
| df.to_csv(DB_FILE, index=False) |
| return msg, load_leaderboard() |
|
|
| |
| X, y = make_classification( |
| n_samples=1000, n_features=2, n_informative=2, n_redundant=0, |
| n_classes=4, n_clusters_per_class=1, class_sep=1.05, random_state=42 |
| ) |
| |
| X_ui, X_secret, y_ui, y_secret = train_test_split(X, y, test_size=700, random_state=42) |
| |
| X_train, X_val, y_train, y_val = train_test_split(X_ui, y_ui, test_size=100, random_state=42) |
|
|
| |
| def train_and_plot(model_type, knn_k, knn_weight, rf_trees, rf_depth, rf_criterion, |
| nn_layers, nn_neurons, nn_activation, nn_lr, nn_solver, nn_alpha): |
| |
| power_draw = 0 |
|
|
| if model_type == "๐ก Proximity Radar (KNN)": |
| weight_map = {"Standard (Uniform)": "uniform", "Distance Focus": "distance"} |
| clf = KNeighborsClassifier(n_neighbors=knn_k, weights=weight_map[knn_weight]) |
| power_draw = knn_k * 5 |
| |
| elif model_type == "๐ธ Swarm Drones (Random Forest)": |
| crit_map = {"Standard (Gini)": "gini", "Chaotic (Entropy)": "entropy"} |
| clf = RandomForestClassifier(n_estimators=rf_trees, max_depth=rf_depth, criterion=crit_map[rf_criterion], random_state=42) |
| power_draw = rf_trees * rf_depth |
| |
| elif model_type == "๐ง Quantum Brain (Neural Network)": |
| architecture = tuple([nn_neurons] * nn_layers) |
| lr_map = {"Cautious (0.001)": 0.001, "Normal (0.01)": 0.01, "Aggressive (0.1)": 0.1} |
| solver_map = {"Warp Drive (Adam)": "adam", "Impulse Drive (SGD)": "sgd"} |
| alpha_map = {"None": 0.0001, "Light": 0.01, "Heavy": 0.1} |
| |
| clf = MLPClassifier( |
| hidden_layer_sizes=architecture, activation=nn_activation, |
| learning_rate_init=lr_map[nn_lr], solver=solver_map[nn_solver], |
| alpha=alpha_map[nn_alpha], max_iter=150, random_state=42 |
| ) |
| power_draw = (nn_layers * nn_neurons) * 10 |
| else: |
| return "0.00%", "0", "F-Tier", None |
|
|
| |
| clf.fit(X_train, y_train) |
| preds = clf.predict(X_secret) |
| acc = accuracy_score(y_secret, preds) |
| acc_text = f"{acc * 100:.2f}%" |
| grade_text = get_grade(acc * 100) |
| |
| |
| fig, ax = plt.subplots(figsize=(7, 6)) |
| fig.patch.set_facecolor('#0b0f19') |
| ax.set_facecolor('#0b0f19') |
| |
| x_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5 |
| y_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5 |
| xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.05), np.arange(y_min, y_max, 0.05)) |
| |
| Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) |
| Z = Z.reshape(xx.shape) |
| |
| cmap_custom = plt.cm.get_cmap('magma', 4) |
| ax.contourf(xx, yy, Z, alpha=0.5, cmap=cmap_custom, antialiased=True) |
| ax.scatter(X_val[:, 0], X_val[:, 1], c=y_val, cmap=cmap_custom, edgecolors='#ffffff', linewidths=0.5, s=40, zorder=3) |
| |
| ax.grid(color='#1e293b', linestyle='--', linewidth=0.5, alpha=0.5, zorder=0) |
| ax.set_title(f"TACTICAL MAP: {model_type.split('(')[0].strip()}", color='#38bdf8', fontsize=14, fontweight='bold', pad=15) |
| ax.set_xticks([]) |
| ax.set_yticks([]) |
| |
| for spine in ax.spines.values(): |
| spine.set_color('#1e293b') |
| spine.set_linewidth(2) |
|
|
| plt.tight_layout() |
| return acc_text, str(power_draw), grade_text, fig |
|
|
| |
| def show_knn(): return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) |
| def show_rf(): return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False) |
| def show_nn(): return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True) |
|
|
| |
| with gr.Blocks(theme=gr.themes.Glass()) as demo: |
| gr.Markdown("# ๐ GALACTIC TARGETING COMMAND") |
| |
| with gr.Tabs(): |
| with gr.Tab("๐ฎ Tactical Console"): |
| gr.Markdown("> **INCOMING TRANSMISSION:** Four alien factions are warping into our sector. Calibrate the defense algorithms. Build the most accurate model to secure an S-Tier rank!") |
| |
| with gr.Row(): |
| with gr.Column(scale=1): |
| model_dropdown = gr.Dropdown( |
| choices=["๐ก Proximity Radar (KNN)", "๐ธ Swarm Drones (Random Forest)", "๐ง Quantum Brain (Neural Network)"], |
| value="๐ก Proximity Radar (KNN)", |
| label="1. Select Hardware Component" |
| ) |
| |
| with gr.Column(visible=True) as knn_block: |
| knn_k = gr.Slider(minimum=1, maximum=50, step=1, value=5, label="Sensor Scan Radius (Neighbors)") |
| knn_weight = gr.Dropdown(choices=["Standard (Uniform)", "Distance Focus"], value="Standard (Uniform)", label="Sensor Priority") |
| |
| with gr.Column(visible=False) as rf_block: |
| rf_trees = gr.Slider(minimum=1, maximum=50, step=1, value=25, label="Drone Fleet Size (Trees)") |
| rf_depth = gr.Slider(minimum=1, maximum=20, step=1, value=5, label="Drone Autonomy (Max Depth)") |
| rf_criterion = gr.Dropdown(choices=["Standard (Gini)", "Chaotic (Entropy)"], value="Standard (Gini)", label="Logic Core") |
| |
| with gr.Column(visible=False) as nn_block: |
| nn_layers = gr.Slider(minimum=1, maximum=4, step=1, value=2, label="Synaptic Layers") |
| nn_neurons = gr.Slider(minimum=5, maximum=50, step=5, value=20, label="Neurons per Layer") |
| with gr.Row(): |
| nn_activation = gr.Dropdown(choices=["relu", "tanh", "logistic"], value="relu", label="Thinking Style") |
| nn_solver = gr.Dropdown(choices=["Warp Drive (Adam)", "Impulse Drive (SGD)"], value="Warp Drive (Adam)", label="Engine") |
| with gr.Row(): |
| nn_lr = gr.Dropdown(choices=["Cautious (0.001)", "Normal (0.01)", "Aggressive (0.1)"], value="Normal (0.01)", label="Learning Speed") |
| nn_alpha = gr.Dropdown(choices=["None", "Light", "Heavy"], value="None", label="L2 Shielding") |
|
|
| gr.Markdown("---") |
| train_btn = gr.Button("โก INITIATE CALIBRATION SEQUENCE โก", variant="primary", size="lg") |
| |
| with gr.Row(): |
| accuracy_display = gr.Textbox(label="Radar Accuracy", value="0.00%", text_align="center") |
| grade_display = gr.Textbox(label="Combat Rank", value="Pending", text_align="center") |
| power_display = gr.Textbox(label="Power Draw (Cost)", value="0", text_align="center") |
| |
| gr.Markdown("---") |
| player_name = gr.Textbox(label="3. Submit Calibration to Fleet Command", placeholder="Enter Callsign / Name...") |
| submit_btn = gr.Button("Transmit Score") |
| status_msg = gr.Markdown("") |
| |
| with gr.Column(scale=2): |
| plot_display = gr.Plot(label="Tactical Display") |
| |
| with gr.Tab("๐ Galactic Leaderboard"): |
| gr.Markdown("### ๐ Rules of Combat:\n1. Highest **Accuracy** takes the lead.\n2. In a tie, the lowest **Power Draw** wins.\n3. If power is also tied, the **Earliest Submission** takes the prize.") |
| refresh_btn = gr.Button("๐ Sync Data with Command") |
| leaderboard_df = gr.Dataframe(value=load_leaderboard, interactive=False) |
|
|
| model_dropdown.change(fn=lambda x: show_knn() if "KNN" in x else (show_rf() if "Random Forest" in x else show_nn()), |
| inputs=model_dropdown, outputs=[knn_block, rf_block, nn_block]) |
| |
| train_btn.click(fn=train_and_plot, |
| inputs=[model_dropdown, knn_k, knn_weight, rf_trees, rf_depth, rf_criterion, |
| nn_layers, nn_neurons, nn_activation, nn_lr, nn_solver, nn_alpha], |
| outputs=[accuracy_display, power_display, grade_display, plot_display]) |
| |
| submit_btn.click(fn=submit_score, inputs=[player_name, accuracy_display, power_display, grade_display], outputs=[status_msg, leaderboard_df]) |
| refresh_btn.click(fn=load_leaderboard, inputs=None, outputs=leaderboard_df) |
|
|
| if __name__ == "__main__": |
| demo.launch() |