Spaces:
Sleeping
Sleeping
Download app.py from microquantum1/system: direct link, hf CLI and curl.
- Browser
- Download file 5.85 kB
-
https://huggingface.co/spaces/microquantum1/system/resolve/main/app.py
- Command line
-
hf download hf://spaces/microquantum1/system/app.py
-
curl -L -o app.py https://huggingface.co/spaces/microquantum1/system/resolve/main/app.py
5.85 kB
| import os | |
| import torch | |
| import gradio as gr | |
| import joblib | |
| import torch.nn as nn | |
| import torch.optim as optim | |
| from datasets import load_dataset | |
| from sklearn.feature_extraction.text import TfidfVectorizer | |
| from sklearn.model_selection import train_test_split | |
| # ------------------------- | |
| # Config | |
| # ------------------------- | |
| MODEL_DIR = "model" | |
| MODEL_PATH = f"{MODEL_DIR}/net.pt" | |
| VEC_PATH = f"{MODEL_DIR}/vectorizer.joblib" | |
| LABELS = ["World", "Sports", "Business", "Sci/Tech"] | |
| NUM_CLASSES = 4 | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| vectorizer = None | |
| model = None | |
| # ------------------------- | |
| # Neural Network (from scratch) | |
| # ------------------------- | |
| class TextNet(nn.Module): | |
| def __init__(self, input_dim): | |
| super().__init__() | |
| self.fc1 = nn.Linear(input_dim, 256) | |
| self.fc2 = nn.Linear(256, 128) | |
| self.out = nn.Linear(128, NUM_CLASSES) | |
| def forward(self, x): | |
| x = torch.relu(self.fc1(x)) | |
| x = torch.relu(self.fc2(x)) | |
| return self.out(x) | |
| # ------------------------- | |
| # Safe Dataset Loader | |
| # ------------------------- | |
| def load_agnews_safe(): | |
| """ | |
| Hugging Face Spaces sometimes caches a deleted commit of ag_news. | |
| This loader forces a fresh revision and retries if needed. | |
| """ | |
| try: | |
| return load_dataset("ag_news", split="train", revision="main") | |
| except Exception: | |
| try: | |
| return load_dataset("ag_news", split="train") | |
| except Exception as e: | |
| raise RuntimeError(f"Dataset failed to load: {e}") | |
| def load_agnews_safe_test(): | |
| try: | |
| return load_dataset("ag_news", split="test", revision="main") | |
| except Exception: | |
| try: | |
| return load_dataset("ag_news", split="test") | |
| except Exception as e: | |
| raise RuntimeError(f"Dataset failed to load: {e}") | |
| # ------------------------- | |
| # Train / Continual Train | |
| # ------------------------- | |
| def train_model(epochs=5, continual=False, progress=gr.Progress()): | |
| global model, vectorizer | |
| progress(0.05, desc="Loading dataset...") | |
| try: | |
| train_data = load_agnews_safe() | |
| test_data = load_agnews_safe_test() | |
| except Exception as e: | |
| return f"Error loading dataset: {e}" | |
| texts = train_data["text"][:6000] | |
| labels = train_data["label"][:6000] | |
| # Vectorizer | |
| if vectorizer is None or not continual: | |
| vectorizer = TfidfVectorizer(max_features=8000, stop_words="english") | |
| X = vectorizer.fit_transform(texts) | |
| else: | |
| X = vectorizer.transform(texts) | |
| y = torch.tensor(labels) | |
| # Split | |
| X_train, X_val, y_train, y_val = train_test_split( | |
| X, y, test_size=0.2, random_state=42 | |
| ) | |
| X_train = torch.tensor(X_train.toarray(), dtype=torch.float32).to(device) | |
| X_val = torch.tensor(X_val.toarray(), dtype=torch.float32).to(device) | |
| y_train = y_train.to(device) | |
| y_val = y_val.to(device) | |
| # Model | |
| if model is None or not continual: | |
| model = TextNet(X_train.shape[1]).to(device) | |
| criterion = nn.CrossEntropyLoss() | |
| optimizer = optim.Adam(model.parameters(), lr=0.001) | |
| history = [] | |
| # Training Loop | |
| for epoch in range(epochs): | |
| model.train() | |
| optimizer.zero_grad() | |
| outputs = model(X_train) | |
| loss = criterion(outputs, y_train) | |
| loss.backward() | |
| optimizer.step() | |
| preds = outputs.argmax(dim=1) | |
| acc = (preds == y_train).float().mean().item() | |
| # Validation | |
| model.eval() | |
| with torch.no_grad(): | |
| val_out = model(X_val) | |
| val_loss = criterion(val_out, y_val).item() | |
| val_acc = (val_out.argmax(dim=1) == y_val).float().mean().item() | |
| history.append( | |
| f"Epoch {epoch+1}/{epochs} | " | |
| f"Loss: {loss.item():.4f} | Acc: {acc:.4f} | " | |
| f"Val Loss: {val_loss:.4f} | Val Acc: {val_acc:.4f}" | |
| ) | |
| progress((epoch + 1) / epochs, desc=f"Epoch {epoch+1}") | |
| # Save | |
| os.makedirs(MODEL_DIR, exist_ok=True) | |
| torch.save(model.state_dict(), MODEL_PATH) | |
| joblib.dump(vectorizer, VEC_PATH) | |
| return "\n".join(history) | |
| # ------------------------- | |
| # Load model | |
| # ------------------------- | |
| def load_model(): | |
| global model, vectorizer | |
| if not os.path.exists(MODEL_PATH) or not os.path.exists(VEC_PATH): | |
| return "No saved model found." | |
| vectorizer = joblib.load(VEC_PATH) | |
| model = TextNet(vectorizer.max_features).to(device) | |
| model.load_state_dict(torch.load(MODEL_PATH, map_location=device)) | |
| model.eval() | |
| return "Model loaded successfully." | |
| # ------------------------- | |
| # Predict | |
| # ------------------------- | |
| def predict(text): | |
| if model is None or vectorizer is None: | |
| return "Train or load a model first." | |
| vec = vectorizer.transform([text]).toarray() | |
| x = torch.tensor(vec, dtype=torch.float32).to(device) | |
| with torch.no_grad(): | |
| logits = model(x) | |
| pred = logits.argmax(dim=1).item() | |
| return LABELS[pred] | |
| # ------------------------- | |
| # Gradio UI | |
| # ------------------------- | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# 🧠 Neural Network AI (From Scratch)") | |
| gr.Markdown("Fully custom neural network with continual learning and safe dataset loading.") | |
| with gr.Row(): | |
| epochs = gr.Slider(1, 10, value=5, step=1, label="Epochs") | |
| continual = gr.Checkbox(label="Continual Learning") | |
| train_btn = gr.Button("Train / Continue Training") | |
| load_btn = gr.Button("Load Saved Model") | |
| log = gr.Textbox(lines=10, label="Training Log") | |
| text_input = gr.Textbox(lines=4, placeholder="Enter news text...") | |
| output = gr.Textbox(label="Prediction") | |
| train_btn.click(train_model, inputs=[epochs, continual], outputs=log) | |
| load_btn.click(load_model, outputs=log) | |
| text_input.submit(predict, inputs=text_input, outputs=output) | |
| demo.launch() | |