CodeLab-AI / app.py
Anupam251272's picture
Create app.py
64b49ea verified
Raw
History Blame Contribute Delete
13.4 kB
import gradio as gr
import numpy as np
import pandas as pd
from typing import Dict
import time
from sklearn.metrics import accuracy_score, mean_squared_error, classification_report
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
# Additional ML helper functions
def evaluate_ml_solution(y_true, y_pred, task_type='classification'):
"""Evaluate ML model predictions"""
if task_type == 'classification':
accuracy = accuracy_score(y_true, y_pred)
report = classification_report(y_true, y_pred)
return f"Accuracy: {accuracy:.4f}\n\nDetailed Report:\n{report}"
else:
mse = mean_squared_error(y_true, y_pred)
rmse = np.sqrt(mse)
return f"MSE: {mse:.4f}\nRMSE: {rmse:.4f}"
# Extended problem set including ML problems
PROBLEM_DATA = {
# Original Algorithm Problems
"Valid Parentheses": {
"type": "algorithm",
"difficulty": "easy",
"description": "Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.",
"test_cases": [
{'input': "()", 'expected': True},
{'input': "()[]{}", 'expected': True},
{'input': "(]", 'expected': False}
],
"sample_input": "()",
"starter_code": """def solution(s: str) -> bool:
# Write your solution here
pass"""
},
# ML Classification Problem
"Binary Classification": {
"type": "ml_classification",
"difficulty": "medium",
"description": "Create a binary classifier for the provided dataset. Features include numerical values, target is binary (0/1).",
"test_cases": [
{
'input': pd.DataFrame({
'feature1': [1.2, 2.3, 3.4, 4.5],
'feature2': [2.1, 3.2, 4.3, 5.4]
}),
'expected': np.array([0, 1, 1, 0])
}
],
"starter_code": """class MLSolution:
def __init__(self):
self.model = None
def fit(self, X, y):
# Implement training logic
pass
def predict(self, X):
# Implement prediction logic
return np.zeros(len(X))"""
},
# Neural Network Problem
"Simple Neural Network": {
"type": "deep_learning",
"difficulty": "hard",
"description": "Implement a simple neural network for binary classification using PyTorch.",
"test_cases": [
{
'input': torch.randn(10, 5), # 10 samples, 5 features
'expected': torch.randint(0, 2, (10,))
}
],
"starter_code": """class NeuralNetwork(nn.Module):
def __init__(self, input_size):
super(NeuralNetwork, self).__init__()
self.layer1 = nn.Linear(input_size, 64)
self.layer2 = nn.Linear(64, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = torch.relu(self.layer1(x))
x = self.sigmoid(self.layer2(x))
return x"""
},
# Regression Problem
"House Price Prediction": {
"type": "ml_regression",
"difficulty": "medium",
"description": "Implement a regression model to predict house prices based on features like size, location, etc.",
"test_cases": [
{
'input': pd.DataFrame({
'size': [1500, 2000, 2500],
'rooms': [3, 4, 5],
'location_score': [8, 7, 9]
}),
'expected': np.array([250000, 300000, 400000])
}
],
"starter_code": """class RegressionSolution:
def __init__(self):
self.model = None
def fit(self, X, y):
# Implement training logic
pass
def predict(self, X):
# Implement prediction logic
return np.zeros(len(X))"""
}
}
def create_sample_data(problem_type: str) -> Dict:
"""Create sample datasets for ML problems"""
if problem_type == 'ml_classification':
X_train = pd.DataFrame(np.random.randn(100, 2), columns=['feature1', 'feature2'])
y_train = np.random.randint(0, 2, 100)
X_test = pd.DataFrame(np.random.randn(20, 2), columns=['feature1', 'feature2'])
y_test = np.random.randint(0, 2, 20)
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
elif problem_type == 'ml_regression':
X_train = pd.DataFrame(np.random.randn(100, 3),
columns=['size', 'rooms', 'location_score'])
y_train = np.random.uniform(200000, 500000, 100)
X_test = pd.DataFrame(np.random.randn(20, 3),
columns=['size', 'rooms', 'location_score'])
y_test = np.random.uniform(200000, 500000, 20)
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
elif problem_type == 'deep_learning':
# Generate sample data for neural network
X_train = torch.randn(100, 5) # 100 samples, 5 features
y_train = torch.randint(0, 2, (100,)) # Binary classification
X_test = torch.randn(20, 5) # 20 samples, 5 features
y_test = torch.randint(0, 2, (20,)) # Binary classification
return {'X_train': X_train, 'y_train': y_train, 'X_test': X_test, 'y_test': y_test}
return None
def run_tests(problem_name: str, user_code: str) -> str:
try:
problem = PROBLEM_DATA[problem_name]
if problem["type"] == "algorithm":
# Execute algorithm problems
namespace = {}
exec(user_code, namespace)
results = []
for i, test in enumerate(problem["test_cases"], 1):
try:
start_time = time.time()
output = namespace["solution"](test["input"])
execution_time = time.time() - start_time
passed = output == test["expected"]
results.append(
f"Test #{i}:\n"
f"Input: {test['input']}\n"
f"Expected: {test['expected']}\n"
f"Got: {output}\n"
f"Time: {execution_time:.6f}s\n"
f"Status: {'✓ PASSED' if passed else '✗ FAILED'}\n"
)
except Exception as e:
results.append(f"Test #{i} Error: {str(e)}\n")
return "\n".join(results)
else:
# Execute ML problems
namespace = {"np": np, "pd": pd, "nn": nn, "torch": torch}
exec(user_code, namespace)
# Create sample data
data = create_sample_data(problem["type"])
if not data:
return "Error: Invalid problem type"
try:
if problem["type"] in ["ml_classification", "ml_regression"]:
# Initialize and train model
model = namespace["MLSolution"]()
model.fit(data["X_train"], data["y_train"])
# Make predictions
predictions = model.predict(data["X_test"])
# Evaluate
eval_result = evaluate_ml_solution(
data["y_test"],
predictions,
"classification" if problem["type"] == "ml_classification" else "regression"
)
return f"Model Evaluation:\n{eval_result}"
elif problem["type"] == "deep_learning":
# Initialize neural network
model = namespace["NeuralNetwork"](data["X_train"].shape[1])
criterion = nn.BCELoss() # Binary cross-entropy loss
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
# Convert data to tensors
X_train = data["X_train"].float()
y_train = data["y_train"].float().view(-1, 1)
X_test = data["X_test"].float()
y_test = data["y_test"].float().view(-1, 1)
# Train the model
for epoch in range(10): # 10 epochs
optimizer.zero_grad()
outputs = model(X_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
# Evaluate the model
with torch.no_grad():
predictions = model(X_test)
predictions = (predictions > 0.5).float() # Convert probabilities to binary predictions
accuracy = (predictions == y_test).float().mean()
return f"Neural Network Evaluation:\nAccuracy: {accuracy.item():.4f}"
except Exception as e:
return f"Error in ML execution: {str(e)}"
except Exception as e:
return f"Error in code execution: {str(e)}"
# Create Gradio interface with enhanced features
def create_interface():
with gr.Blocks(title="Advanced LeetCode & ML Testing Platform") as iface:
# All components and event handlers must be defined within this 'with' block
gr.Markdown("# Advanced LeetCode & ML Testing Platform")
with gr.Tabs():
with gr.Tab("Problem Solving"):
problem_dropdown = gr.Dropdown(
choices=list(PROBLEM_DATA.keys()),
label="Select Problem"
)
difficulty_display = gr.Textbox(label="Difficulty")
problem_type = gr.Textbox(label="Problem Type")
description_text = gr.Textbox(label="Description", lines=5)
code_input = gr.Textbox(label="Your Code", lines=10, value="")
results_output = gr.Textbox(label="Test Results", value="", lines=10)
with gr.Row():
run_button = gr.Button("Run Tests")
clear_button = gr.Button("Clear Code")
# Event handler for Run Tests button (inside Blocks context)
run_button.click(
run_tests,
inputs=[problem_dropdown, code_input],
outputs=[results_output]
)
# Event handler for Clear Code button (inside Blocks context)
clear_button.click(
lambda: "",
inputs=[],
outputs=[code_input]
)
# Event handler for problem selection (inside Blocks context)
def update_problem_info(problem_name):
problem = PROBLEM_DATA[problem_name]
return (
problem["difficulty"],
problem["type"],
problem["description"],
problem["starter_code"],
"" # Clear results
)
problem_dropdown.change(
update_problem_info,
inputs=[problem_dropdown],
outputs=[
difficulty_display,
problem_type,
description_text,
code_input,
results_output
]
)
with gr.Tab("Visualization"):
with gr.Row():
plot_type = gr.Dropdown(
choices=["Learning Curve", "Confusion Matrix", "Feature Importance"],
label="Select Plot Type"
)
visualize_button = gr.Button("Generate Visualization")
plot_output = gr.Plot(label="Visualization")
# Event handler for visualization
def generate_visualization(plot_type):
if plot_type == "Learning Curve":
# Example learning curve
plt.figure()
plt.plot([0, 1, 2, 3, 4], [0.8, 0.7, 0.6, 0.5, 0.4], label="Training Loss")
plt.plot([0, 1, 2, 3, 4], [0.9, 0.8, 0.7, 0.6, 0.5], label="Validation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.title("Learning Curve")
plt.legend()
return plt
else:
return None
visualize_button.click(
generate_visualization,
inputs=[plot_type],
outputs=[plot_output]
)
return iface
if __name__ == "__main__":
iface = create_interface()
iface.launch()