Eric22333 commited on
Commit
3fc1a98
·
verified ·
1 Parent(s): 9a5a57d

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +64 -0
pipeline.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PreTrainedModel, PretrainedConfig
2
+ from tensorflow.keras.models import load_model
3
+ from tensorflow.keras.preprocessing.text import tokenizer_from_json
4
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
5
+ import numpy as np
6
+ import json
7
+
8
+ class NewsClassifierConfig(PretrainedConfig):
9
+ model_type = "news_classifier"
10
+
11
+ def __init__(
12
+ self,
13
+ max_length=41, # Modified to match model input shape
14
+ vocab_size=74934, # Modified based on embedding layer size
15
+ embedding_dim=128, # Added to match model architecture
16
+ hidden_size=64, # Matches final LSTM layer
17
+ num_labels=2,
18
+ **kwargs
19
+ ):
20
+ self.max_length = max_length
21
+ self.vocab_size = vocab_size
22
+ self.embedding_dim = embedding_dim
23
+ self.hidden_size = hidden_size
24
+ self.num_labels = num_labels
25
+ super().__init__(**kwargs)
26
+
27
+ class NewsClassifier(PreTrainedModel):
28
+ config_class = NewsClassifierConfig
29
+ base_model_prefix = "news_classifier"
30
+
31
+ def __init__(self, config):
32
+ super().__init__(config)
33
+ self.model = None # Will be loaded in post_init
34
+ self.tokenizer = None
35
+
36
+ def post_init(self):
37
+ """Load model and tokenizer after initialization"""
38
+ self.model = load_model('news_classifier.h5')
39
+ with open('tokenizer.json', 'r') as f:
40
+ tokenizer_data = json.load(f)
41
+ self.tokenizer = tokenizer_from_json(tokenizer_data)
42
+
43
+ def forward(self, text_input):
44
+ if not self.model or not self.tokenizer:
45
+ self.post_init()
46
+
47
+ if isinstance(text_input, str):
48
+ text_input = [text_input]
49
+
50
+ sequences = self.tokenizer.texts_to_sequences(text_input)
51
+ padded = pad_sequences(sequences, maxlen=self.config.max_length)
52
+ predictions = self.model.predict(padded, verbose=0)
53
+
54
+ results = []
55
+ for pred in predictions:
56
+ # Convert from 2-class output to single score
57
+ score = float(pred[1]) # Assuming pred[1] is the probability for "foxnews"
58
+ label = "foxnews" if score > 0.5 else "nbc"
59
+ results.append({
60
+ "label": label,
61
+ "score": score if label == "foxnews" else 1 - score
62
+ })
63
+
64
+ return results[0] if len(text_input) == 1 else results