Spaces:
Build error
Build error
init
Browse filesFiles changed (5)
- .gitignoreAdded+1
- .gradio/certificate.pemAdded+31
- app.pyAdded+135
- best_model.pthAdded+3
- requirements.txtAdded+70
1.venv12345678910111213141516171819202122232425262728293031-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135import reimport gradio as grfrom datasets import load_datasetimport torchfrom torch.utils.data import random_splitfrom collections import Counterimport torch.nn as nn
class LSTMClassifier(nn.Module): def __init__(self, vocab_size, embedding_dim=200, hidden_dim=256): super(LSTMClassifier, self).__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)
self.lstm = nn.LSTM( embedding_dim, hidden_dim, num_layers=2, batch_first=True, bidirectional=True, dropout=0.3, )
# Dropout layer self.dropout = nn.Dropout(0.4)
# Additional dense layers self.fc1 = nn.Linear(hidden_dim * 2, hidden_dim) self.fc2 = nn.Linear(hidden_dim, 2)
def forward(self, x): embedded = self.embedding(x)
lstm_out, (hidden, cell) = self.lstm(embedded)
# Concatenate forward and backward hidden states hidden = torch.cat((hidden[-2, :, :], hidden[-1, :, :]), dim=1) hidden = self.dropout(hidden)
# Additional layer with ReLU activation hidden = torch.relu(self.fc1(hidden)) hidden = self.dropout(hidden)
# Final classification layer out = self.fc2(hidden) return out
def create_vocabulary(ds, max_words=10000): word2idx = { "<PAD>": 0, "<UNK>": 1, } words = [] for example in ds: text = example["sms"] text = text.lower() text = re.sub(r"[^\w\s]", "", text) words.extend(text.split())
word_counts = Counter(words) common_words = word_counts.most_common(max_words - 2) for word, _ in common_words: word2idx[word] = len(word2idx)
return word2idx
def create_splits(ds): # 80/20 split full_dataset = ds['train'] train_size = int(0.8 * len(full_dataset)) test_size = len(full_dataset) - train_size
train_dataset, test_dataset = random_split( full_dataset, [train_size, test_size], generator=torch.Generator().manual_seed(42), ) return train_dataset, test_dataset
ds = load_dataset("ucirvine/sms_spam")train_dataset, test_dataset = create_splits(ds)vocab = create_vocabulary(train_dataset)
# First recreate the model architecturemodel = LSTMClassifier(len(vocab), 100)# Load the saved state dictmodel.load_state_dict(torch.load('best_model.pth'))device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
def predict_text(model, text, word2idx, device, max_length=50): # Set model to evaluation mode model.eval()
# Preprocess the text (same as training) text = text.lower() words = text.split()
# Convert words to indices indices = [word2idx.get(word, word2idx['<UNK>']) for word in words]
# Pad or truncate if len(indices) < max_length: indices += [word2idx['<PAD>']] * (max_length - len(indices)) else: indices = indices[:max_length]
# Convert to tensor with torch.no_grad(): input_tensor = torch.tensor(indices).unsqueeze( 0).to(device) # Add batch dimension outputs = model(input_tensor) probabilities = torch.softmax(outputs, dim=1) prediction = torch.argmax(outputs, dim=1)
return { 'prediction': 'spam' if prediction.item() == 1 else 'ham', 'confidence': probabilities[0][prediction].item() }
interface = gr.Interface( fn=lambda text: predict_text(model, text, vocab, device), inputs=gr.Textbox(lines=2, placeholder="Enter your text here..."), outputs=gr.Textbox(), title="SMS Spam Classifier", description="Enter a text message to predict if it's spam or ham.",)
interface.launch(share=True)123version https://git-lfs.github.com/spec/v1oid sha256:29dad210d08207edb98d9c2052f9822968170e10121292a578f787d438430e2fsize 1315830612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970aiofiles==23.2.1aiohappyeyeballs==2.6.1aiohttp==3.11.14aiosignal==1.3.2annotated-types==0.7.0anyio==4.9.0attrs==25.3.0certifi==2025.1.31charset-normalizer==3.4.1click==8.1.8datasets==3.4.1dill==0.3.8fastapi==0.115.12ffmpy==0.5.0filelock==3.18.0frozenlist==1.5.0fsspec==2024.12.0gradio==5.23.1gradio_client==1.8.0groovy==0.1.2h11==0.14.0httpcore==1.0.7httpx==0.28.1huggingface-hub==0.29.3idna==3.10Jinja2==3.1.6markdown-it-py==3.0.0MarkupSafe==3.0.2mdurl==0.1.2mpmath==1.3.0multidict==6.2.0multiprocess==0.70.16networkx==3.4.2numpy==2.2.4orjson==3.10.16packaging==24.2pandas==2.2.3pillow==11.1.0propcache==0.3.1pyarrow==19.0.1pydantic==2.10.6pydantic_core==2.27.2pydub==0.25.1Pygments==2.19.1python-dateutil==2.9.0.post0python-multipart==0.0.20pytz==2025.2PyYAML==6.0.2requests==2.32.3rich==13.9.4ruff==0.11.2safehttpx==0.1.6semantic-version==2.10.0shellingham==1.5.4six==1.17.0sniffio==1.3.1starlette==0.46.1sympy==1.13.1tomlkit==0.13.2torch==2.6.0torchvision==0.21.0tqdm==4.67.1typer==0.15.2typing_extensions==4.13.0tzdata==2025.2urllib3==2.3.0uvicorn==0.34.0websockets==15.0.1xxhash==3.5.0yarl==1.18.3.gitignoreAdded+1
.gradio/certificate.pemAdded+31
app.pyAdded+135
best_model.pthAdded+3
requirements.txtAdded+70