BhuiyanMasum commited on
Commit
9c70e7b
·
1 Parent(s): 214864d

upload api codes

Browse files
Files changed (5) hide show
  1. Dockerfile +13 -0
  2. app.py +113 -0
  3. model_weights.pth +3 -0
  4. requirements.txt +5 -0
  5. vocab.pkl +3 -0
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
app.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from fastapi import FastAPI, HTTPException
3
+ from pydantic import BaseModel
4
+ import torch.nn as nn
5
+ import pickle
6
+ import re
7
+
8
+ token_2_id = None
9
+ # Load the dictionary later
10
+ with open(r"vocab.pkl", "rb") as f:
11
+ token_2_id = pickle.load(f)
12
+ print(token_2_id)
13
+
14
+
15
+ def normalize(text):
16
+ text = text.lower()
17
+ text = re.sub(r'[^a-z0-9\s]', '', text)
18
+ text = ' '.join(text.split())
19
+ return text
20
+
21
+
22
+ def tokenize(text):
23
+ tokens = text.split()
24
+ return tokens
25
+
26
+
27
+ def convert_tokens_2_ids(tokens):
28
+ input_ids = [
29
+ token_2_id.get(token, token_2_id['<UNK>']) for token in tokens
30
+ ]
31
+ return input_ids
32
+
33
+
34
+ def process_text(text, aspect):
35
+ text_aspect_pair = text + ' ' + aspect
36
+ normalized_text = normalize(text_aspect_pair)
37
+ tokens = tokenize(normalized_text)
38
+ input_ids = convert_tokens_2_ids(tokens)
39
+ input_ids = torch.tensor(input_ids).unsqueeze(0)
40
+ return input_ids
41
+
42
+
43
+ class ABSA(nn.Module):
44
+ def __init__(self, vocab_size, num_labels=3):
45
+ super(ABSA, self).__init__()
46
+ self.vocab_size = vocab_size
47
+ self.num_labels = num_labels
48
+ self.embedding_layer = nn.Embedding(
49
+ num_embeddings=vocab_size, embedding_dim=256
50
+ )
51
+ self.lstm_layer = nn.LSTM(
52
+ input_size=256,
53
+ hidden_size=512,
54
+ batch_first=True,
55
+ )
56
+
57
+ self.fc_layer = nn.Linear(
58
+ in_features=512,
59
+ out_features=self.num_labels
60
+ )
61
+
62
+ def forward(self, x):
63
+ embeddings = self.embedding_layer(x)
64
+ lstm_out, _ = self.lstm_layer(embeddings)
65
+ logits = self.fc_layer(lstm_out[:, -1, :])
66
+ return logits
67
+
68
+
69
+ model = ABSA(vocab_size=len(token_2_id.keys()), num_labels=3)
70
+ model.load_state_dict(torch.load(r'model_weights.pth'))
71
+ model.eval()
72
+
73
+ print("Model loaded successfully")
74
+
75
+ app = FastAPI()
76
+
77
+
78
+ # space url = "https://masumbhuiyan-myabsaservices.hf.space/"
79
+ # greet api = "https://masumbhuiyan-myabsaservices.hf.space/greet"
80
+ # post api = "https://masumbhuiyan-myabsaservices.hf.space/predict"
81
+ @app.get("/greet")
82
+ def greet_json():
83
+ return {"message": "Hello World"}
84
+
85
+
86
+ class TextAspectInput(BaseModel):
87
+ text: str
88
+ aspect: str
89
+
90
+
91
+ SENTIMENT_LABELS = {0: "Negative", 1: "Neutral", 2: "Positive"}
92
+
93
+
94
+ @app.post("/predict")
95
+ async def predict_sentiment(input_data: TextAspectInput):
96
+ try:
97
+ text = input_data.text
98
+ aspect = input_data.aspect
99
+ input_ids = process_text(text, aspect)
100
+
101
+ try:
102
+ with torch.no_grad():
103
+ logits = model(input_ids)
104
+ probs = torch.softmax(logits, dim=-1)
105
+ prediction = probs.argmax(dim=-1).item()
106
+ sentiment = SENTIMENT_LABELS[prediction]
107
+ except Exception as e:
108
+ raise Exception(e)
109
+
110
+ return {"sentiment": sentiment, "probabilities": probs.squeeze().tolist()}
111
+ except Exception as e:
112
+ raise HTTPException(status_code=500, detail=str(e))
113
+
model_weights.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b1a6752d09f7a562dd93c6d857987c4df789908e132287bef226ac82c6c2a80
3
+ size 10208198
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ numpy
4
+ Pillow
5
+ torch
vocab.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2e195b47d3a84c730ff3a7f25df52b335174ba06914d9404bffa7f4422603d60
3
+ size 47213