Upload 2 files
Browse files- flaskapp.py +20 -0
- minilm_keyword_pred.py +151 -0
flaskapp.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from minilm_keyword_pred import predict_on_text
|
| 5 |
+
|
| 6 |
+
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
|
| 7 |
+
print('dev', device)
|
| 8 |
+
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
|
| 11 |
+
@app.route('/get_keywords', methods=['POST'])
|
| 12 |
+
def get_keywords():
|
| 13 |
+
text = request.json.get('text', '')
|
| 14 |
+
if not text: return jsonify({"error": "The 'text' field is required."}), 400
|
| 15 |
+
groups = predict_on_text(text)['predicted_groups_with_scores']
|
| 16 |
+
groups = [{'keyword': x[0], 'score': float(x[1])} for x in groups]
|
| 17 |
+
return jsonify(groups)
|
| 18 |
+
|
| 19 |
+
if __name__ == "__main__":
|
| 20 |
+
app.run(host="0.0.0.0", port=14005, debug=True, use_reloader=False)
|
minilm_keyword_pred.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import pickle
|
| 4 |
+
from transformers import AutoTokenizer, AutoModel
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
OFFLINE_MODEL_PATH = "all-MiniLM-L6-v2"
|
| 9 |
+
|
| 10 |
+
# ==============================================================================
|
| 11 |
+
# STEP 1: DEFINE THE MODEL ARCHITECTURE
|
| 12 |
+
# This MUST be the exact same class definition you used for training.
|
| 13 |
+
# ==============================================================================
|
| 14 |
+
class ImprovedMultiTaskClassifier(nn.Module):
|
| 15 |
+
def __init__(self, model_name, num_keywords, num_groups, dropout_rate=0.1):
|
| 16 |
+
super(ImprovedMultiTaskClassifier, self).__init__()
|
| 17 |
+
self.transformer = AutoModel.from_pretrained(model_name)
|
| 18 |
+
hidden_size = self.transformer.config.hidden_size
|
| 19 |
+
|
| 20 |
+
self.keyword_classifier = nn.Sequential(
|
| 21 |
+
nn.Linear(hidden_size, hidden_size),
|
| 22 |
+
nn.LayerNorm(hidden_size), nn.ReLU(), nn.Dropout(dropout_rate),
|
| 23 |
+
nn.Linear(hidden_size, hidden_size // 2),
|
| 24 |
+
nn.LayerNorm(hidden_size // 2), nn.ReLU(), nn.Dropout(dropout_rate),
|
| 25 |
+
nn.Linear(hidden_size // 2, num_keywords)
|
| 26 |
+
)
|
| 27 |
+
self.group_classifier = nn.Sequential(
|
| 28 |
+
nn.Linear(hidden_size, hidden_size),
|
| 29 |
+
nn.LayerNorm(hidden_size), nn.ReLU(), nn.Dropout(dropout_rate),
|
| 30 |
+
nn.Linear(hidden_size, hidden_size // 2),
|
| 31 |
+
nn.LayerNorm(hidden_size // 2), nn.ReLU(), nn.Dropout(dropout_rate),
|
| 32 |
+
nn.Linear(hidden_size // 2, num_groups)
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def forward(self, input_ids, attention_mask):
|
| 36 |
+
outputs = self.transformer(input_ids=input_ids, attention_mask=attention_mask)
|
| 37 |
+
token_embeddings = outputs.last_hidden_state
|
| 38 |
+
attention_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
| 39 |
+
sum_embeddings = torch.sum(token_embeddings * attention_mask_expanded, 1)
|
| 40 |
+
sum_mask = torch.clamp(attention_mask_expanded.sum(1), min=1e-9)
|
| 41 |
+
pooled_output = sum_embeddings / sum_mask
|
| 42 |
+
keyword_logits = self.keyword_classifier(pooled_output)
|
| 43 |
+
group_logits = self.group_classifier(pooled_output)
|
| 44 |
+
return keyword_logits, group_logits
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# ==============================================================================
|
| 48 |
+
# STEP 2: LOAD ALL SAVED COMPONENTS
|
| 49 |
+
# ==============================================================================
|
| 50 |
+
print("Loading all components for inference...")
|
| 51 |
+
|
| 52 |
+
# Set device
|
| 53 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 54 |
+
print(f"Using device: {device}")
|
| 55 |
+
|
| 56 |
+
# Load config
|
| 57 |
+
with open('minilm_keyword_classifier_gemini/inference_config.pkl', 'rb') as f:
|
| 58 |
+
config = pickle.load(f)
|
| 59 |
+
|
| 60 |
+
# *** IMPORTANT: Override the model_name to use the local path ***
|
| 61 |
+
config['model_name'] = OFFLINE_MODEL_PATH
|
| 62 |
+
# Load tokenizer from the same offline path
|
| 63 |
+
tokenizer = AutoTokenizer.from_pretrained(OFFLINE_MODEL_PATH)
|
| 64 |
+
|
| 65 |
+
# Load tokenizer
|
| 66 |
+
tokenizer = AutoTokenizer.from_pretrained('minilm_keyword_classifier_gemini/inference_tokenizer')
|
| 67 |
+
|
| 68 |
+
# Load label encoders
|
| 69 |
+
with open('minilm_keyword_classifier_gemini/inference_mlb_keywords.pkl', 'rb') as f:
|
| 70 |
+
mlb_keywords = pickle.load(f)
|
| 71 |
+
with open('minilm_keyword_classifier_gemini/inference_mlb_groups.pkl', 'rb') as f:
|
| 72 |
+
mlb_groups = pickle.load(f)
|
| 73 |
+
|
| 74 |
+
# Instantiate the model architecture
|
| 75 |
+
num_keywords = len(mlb_keywords.classes_)
|
| 76 |
+
num_groups = len(mlb_groups.classes_)
|
| 77 |
+
model = ImprovedMultiTaskClassifier(config['model_name'], num_keywords, num_groups).to(device)
|
| 78 |
+
|
| 79 |
+
# Load the trained weights
|
| 80 |
+
model.load_state_dict(torch.load('minilm_keyword_classifier_gemini/inference_model.pth', map_location=device))
|
| 81 |
+
|
| 82 |
+
# Set model to evaluation mode (very important!)
|
| 83 |
+
model.eval()
|
| 84 |
+
|
| 85 |
+
print("✅ All components loaded and model is ready for inference.")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ==============================================================================
|
| 89 |
+
# STEP 3: CREATE THE PREDICTION FUNCTION (MODIFIED TO INCLUDE SCORES)
|
| 90 |
+
# ==============================================================================
|
| 91 |
+
def predict_on_text(text: str):
|
| 92 |
+
"""
|
| 93 |
+
Takes a string of text and returns the predicted keywords and groups
|
| 94 |
+
along with their confidence scores.
|
| 95 |
+
"""
|
| 96 |
+
with torch.no_grad():
|
| 97 |
+
encoding = tokenizer(
|
| 98 |
+
text,
|
| 99 |
+
truncation=True,
|
| 100 |
+
padding='max_length',
|
| 101 |
+
max_length=512,
|
| 102 |
+
return_tensors='pt'
|
| 103 |
+
)
|
| 104 |
+
input_ids = encoding['input_ids'].to(device)
|
| 105 |
+
attention_mask = encoding['attention_mask'].to(device)
|
| 106 |
+
|
| 107 |
+
keyword_logits, group_logits = model(input_ids, attention_mask)
|
| 108 |
+
|
| 109 |
+
keyword_probs = torch.sigmoid(keyword_logits).cpu().numpy()[0]
|
| 110 |
+
group_probs = torch.sigmoid(group_logits).cpu().numpy()[0]
|
| 111 |
+
|
| 112 |
+
kw_threshold = config['optimal_keyword_threshold']
|
| 113 |
+
gr_threshold = config['optimal_group_threshold']
|
| 114 |
+
|
| 115 |
+
# --- MODIFICATION START ---
|
| 116 |
+
# Get keywords that are above the threshold
|
| 117 |
+
kw_indices = np.where(keyword_probs > kw_threshold)[0]
|
| 118 |
+
predicted_keywords_with_scores = [
|
| 119 |
+
(mlb_keywords.classes_[i], keyword_probs[i]) for i in kw_indices
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
# Get groups that are above the threshold
|
| 123 |
+
gr_indices = np.where(group_probs > gr_threshold)[0]
|
| 124 |
+
predicted_groups_with_scores = [
|
| 125 |
+
(mlb_groups.classes_[i], group_probs[i]) for i in gr_indices
|
| 126 |
+
]
|
| 127 |
+
|
| 128 |
+
# Sort predictions by score in descending order
|
| 129 |
+
predicted_keywords_with_scores.sort(key=lambda x: x[1], reverse=True)
|
| 130 |
+
predicted_groups_with_scores.sort(key=lambda x: x[1], reverse=True)
|
| 131 |
+
# --- MODIFICATION END ---
|
| 132 |
+
|
| 133 |
+
return {
|
| 134 |
+
'predicted_keywords_with_scores': predicted_keywords_with_scores,
|
| 135 |
+
'predicted_groups_with_scores': predicted_groups_with_scores,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
# list through all csv files in automarked\todo folder. Read the content column and loop through all the content there as text
|
| 141 |
+
# for file in glob.glob('automarked\\todo\\*.csv'):
|
| 142 |
+
# with open(file, 'r', newline='', encoding='utf-8', errors='ignore') as f:
|
| 143 |
+
# reader = csv.DictReader(f)
|
| 144 |
+
# for row in reader:
|
| 145 |
+
# text = row['content']
|
| 146 |
+
|
| 147 |
+
text = """I want you to understand, people think there are many problems in the world. There are no many problems in the world. There's only one problem in the world – human being. What other problem, I'm asking"""
|
| 148 |
+
|
| 149 |
+
dpred = predict_on_text(text)
|
| 150 |
+
for d in dpred['predicted_groups_with_scores']:
|
| 151 |
+
print(d[0], d[1], d[1] > 0.5)
|