ngamulin commited on
Commit
b3b4b75
·
verified ·
1 Parent(s): a42cde6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import gradio as gr
4
+ from huggingface_hub import hf_hub_download
5
+
6
+ REPO_ID = "SentilyticsOPJ/lstm_model" # <-- change to your model repo
7
+ FILENAME = "lstm_model.pt"
8
+
9
+
10
+ class TextBiLSTM(nn.Module):
11
+ def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
12
+ super().__init__()
13
+ self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=0)
14
+ self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
15
+ self.fc = nn.Linear(hidden_dim * 2, num_classes)
16
+
17
+ def forward(self, x):
18
+ x = self.embedding(x)
19
+ _, (hidden, _) = self.lstm(x)
20
+ x = torch.cat([hidden[0], hidden[1]], dim=1)
21
+ return self.fc(x)
22
+
23
+ path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME)
24
+ obj = torch.load(path, map_location="cpu", weights_only=False)
25
+ sd = obj["state_dict"]
26
+
27
+ vocab_size, embed_dim = sd["embedding.weight"].shape
28
+ hidden_dim = sd["lstm.weight_hh_l0"].shape[1]
29
+ num_classes = sd["fc.weight"].shape[0]
30
+
31
+ model = TextBiLSTM(vocab_size, embed_dim, hidden_dim, num_classes)
32
+ model.load_state_dict(sd)
33
+ model.eval()
34
+
35
+ word2id = obj["word2id"]
36
+ labels = obj["label_classes"]
37
+ max_len = obj["max_len"]
38
+
39
+
40
+ def predict(text):
41
+ if not text.strip():
42
+ return {}
43
+ ids = [word2id.get(t, 1) for t in text.lower().split()][:max_len]
44
+ ids += [0] * (max_len - len(ids))
45
+ with torch.no_grad():
46
+ probs = torch.softmax(model(torch.tensor(ids).unsqueeze(0)), dim=1)[0]
47
+ return {labels[i]: float(probs[i]) for i in range(len(labels))}
48
+
49
+ gr.Interface(fn=predict, inputs="text", outputs="text").launch()