Upload inference.py with huggingface_hub
Browse files- inference.py +78 -140
inference.py
CHANGED
|
@@ -1,157 +1,95 @@
|
|
| 1 |
import torch
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
import pickle
|
| 5 |
import json
|
|
|
|
| 6 |
import os
|
| 7 |
|
| 8 |
-
class
|
| 9 |
-
def __init__(self,
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
self.
|
| 17 |
-
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
self.model.eval()
|
| 24 |
|
| 25 |
-
|
| 26 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
"""Load classifier and label embeddings if they exist"""
|
| 30 |
-
try:
|
| 31 |
-
# Load classifier if exists
|
| 32 |
-
classifier_path = os.path.join(self.model_path, "classifier.pkl")
|
| 33 |
-
if os.path.exists(classifier_path):
|
| 34 |
-
with open(classifier_path, 'rb') as f:
|
| 35 |
-
self.classifier = pickle.load(f)
|
| 36 |
-
else:
|
| 37 |
-
self.classifier = None
|
| 38 |
-
|
| 39 |
-
# Load label embeddings if exists
|
| 40 |
-
embeddings_path = os.path.join(self.model_path, "label_embeddings.pkl")
|
| 41 |
-
if os.path.exists(embeddings_path):
|
| 42 |
-
with open(embeddings_path, 'rb') as f:
|
| 43 |
-
self.label_embeddings = pickle.load(f)
|
| 44 |
-
else:
|
| 45 |
-
self.label_embeddings = None
|
| 46 |
-
|
| 47 |
-
except Exception as e:
|
| 48 |
-
print(f"Warning: Could not load additional components: {e}")
|
| 49 |
-
self.classifier = None
|
| 50 |
-
self.label_embeddings = None
|
| 51 |
|
| 52 |
-
def
|
| 53 |
-
|
| 54 |
-
|
|
|
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
Returns:
|
| 61 |
-
dict: Prediction results with labels and probabilities
|
| 62 |
-
"""
|
| 63 |
-
# Tokenize input
|
| 64 |
-
inputs = self.tokenizer(
|
| 65 |
-
text,
|
| 66 |
-
return_tensors="pt",
|
| 67 |
-
truncation=True,
|
| 68 |
-
max_length=512,
|
| 69 |
-
padding=True
|
| 70 |
-
)
|
| 71 |
-
inputs = {k: v.to(self.device) for k, v in inputs.items()}
|
| 72 |
-
|
| 73 |
-
# Get model predictions
|
| 74 |
-
with torch.no_grad():
|
| 75 |
-
outputs = self.model(**inputs)
|
| 76 |
-
logits = outputs.logits
|
| 77 |
-
probabilities = torch.nn.functional.softmax(logits, dim=-1)
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
|
| 82 |
-
|
| 83 |
-
results = []
|
| 84 |
-
for i in range(top_k):
|
| 85 |
-
label_id = top_indices[0][i].item()
|
| 86 |
-
probability = top_probs[0][i].item()
|
| 87 |
-
label = self.model.config.id2label[label_id]
|
| 88 |
-
|
| 89 |
-
results.append({
|
| 90 |
-
"label": label,
|
| 91 |
-
"label_id": label_id,
|
| 92 |
-
"probability": probability
|
| 93 |
-
})
|
| 94 |
-
|
| 95 |
-
return {
|
| 96 |
-
"predictions": results,
|
| 97 |
-
"input_text": text,
|
| 98 |
-
"model_info": {
|
| 99 |
-
"model_name": self.model.config._name_or_path,
|
| 100 |
-
"num_labels": self.model.config.num_labels,
|
| 101 |
-
"device": str(self.device)
|
| 102 |
-
}
|
| 103 |
-
}
|
| 104 |
|
| 105 |
-
def
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
model_path = "." # Current directory
|
| 139 |
-
classifier = SteelMaterialClassifier(model_path)
|
| 140 |
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
"์ฒ ๊ด์์ ๊ณ ๋ก์์ ํ์ํ์ฌ ์ ์ฒ ์ ์ ์กฐํ๋ ๊ณผ์ ",
|
| 144 |
-
"์ฒ์ฐ๊ฐ์ค๋ฅผ ์ฐ๋ฃ๋ก ์ฌ์ฉํ์ฌ ๊ณ ๋ก๋ฅผ ๊ฐ์ด",
|
| 145 |
-
"์ํ์์ ์ฒจ๊ฐํ์ฌ ์ฌ๋๊ทธ๋ฅผ ํ์ฑ"
|
| 146 |
-
]
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
|
|
|
| 4 |
import json
|
| 5 |
+
import numpy as np
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
class IntegratedClassifier(nn.Module):
|
| 9 |
+
def __init__(self, config):
|
| 10 |
+
super().__init__()
|
| 11 |
+
self.fc1 = nn.Linear(config['input_size'], config['hidden_size'])
|
| 12 |
+
self.fc2 = nn.Linear(config['hidden_size'], config['intermediate_size'])
|
| 13 |
+
self.fc3 = nn.Linear(config['intermediate_size'], config['num_labels'])
|
| 14 |
+
self.dropout = nn.Dropout(0.3)
|
| 15 |
+
self.id2label = config['id2label']
|
| 16 |
+
self.input_size = config['input_size']
|
|
|
|
| 17 |
|
| 18 |
+
def forward(self, text):
|
| 19 |
+
# ๋ด๋ถ์ ์ผ๋ก TF-IDF ๋ฒกํฐํ ์ํ
|
| 20 |
+
text_vector = self._vectorize_text(text)
|
| 21 |
+
text_tensor = torch.FloatTensor(text_vector).unsqueeze(0)
|
|
|
|
| 22 |
|
| 23 |
+
x = F.relu(self.fc1(text_tensor))
|
| 24 |
+
x = self.dropout(x)
|
| 25 |
+
x = F.relu(self.fc2(x))
|
| 26 |
+
x = self.dropout(x)
|
| 27 |
+
x = self.fc3(x)
|
| 28 |
|
| 29 |
+
return x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
def _vectorize_text(self, text):
|
| 32 |
+
# ๊ฐ๋จํ TF-IDF ๊ตฌํ
|
| 33 |
+
words = text.lower().split()
|
| 34 |
+
vector = np.zeros(self.input_size)
|
| 35 |
|
| 36 |
+
for word in words:
|
| 37 |
+
for i in range(self.input_size):
|
| 38 |
+
if word in str(i) or str(i) in word:
|
| 39 |
+
vector[i] += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
if np.sum(vector) > 0:
|
| 42 |
+
vector = vector / np.sum(vector)
|
| 43 |
|
| 44 |
+
return vector
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
+
def predict(self, text):
|
| 47 |
+
self.eval()
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
outputs = self.forward(text)
|
| 50 |
+
probabilities = F.softmax(outputs, dim=1)
|
| 51 |
+
predicted_class = torch.argmax(probabilities, dim=1).item()
|
| 52 |
+
|
| 53 |
+
label = self.id2label[str(predicted_class)]
|
| 54 |
+
confidence = probabilities[0][predicted_class].item()
|
| 55 |
|
| 56 |
+
return label, confidence
|
| 57 |
+
|
| 58 |
+
# ์ ์ญ ๋ณ์๋ก ๋ชจ๋ธ ์ ์ฅ
|
| 59 |
+
model = None
|
| 60 |
+
|
| 61 |
+
def load_model():
|
| 62 |
+
"""๋ชจ๋ธ ๋ก๋"""
|
| 63 |
+
global model
|
| 64 |
|
| 65 |
+
# ์ค์ ํ์ผ ๋ก๋
|
| 66 |
+
config_path = os.path.join(os.getcwd(), "config.json")
|
| 67 |
+
with open(config_path, 'r', encoding='utf-8') as f:
|
| 68 |
+
config = json.load(f)
|
| 69 |
+
|
| 70 |
+
# ๋ชจ๋ธ ์์ฑ ๋ฐ ๋ก๋
|
| 71 |
+
model = IntegratedClassifier(config)
|
| 72 |
+
model_path = os.path.join(os.getcwd(), "integrated_model.bin")
|
| 73 |
+
model.load_state_dict(torch.load(model_path, map_location='cpu'))
|
| 74 |
+
model.eval()
|
| 75 |
+
|
| 76 |
+
return model
|
| 77 |
|
| 78 |
+
def predict(text):
|
| 79 |
+
"""์์ธก ํจ์"""
|
| 80 |
+
global model
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
if model is None:
|
| 83 |
+
model = load_model()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
label, confidence = model.predict(text)
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
"label": label,
|
| 89 |
+
"confidence": confidence,
|
| 90 |
+
"text": text
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
# ๋ชจ๋ธ ์ด๊ธฐ ๋ก๋
|
| 94 |
+
if __name__ == "__main__":
|
| 95 |
+
load_model()
|