Jiahuita commited on
Commit
700431a
1 Parent(s): 5aafe28

Deleted app

Browse files
Files changed (4) hide show
  1. README.md +1 -2
  2. app.py +0 -84
  3. config.json +2 -2
  4. pipeline.py +41 -23
README.md CHANGED
@@ -56,9 +56,8 @@ You can use this model directly with a FastAPI endpoint:
56
  ```python
57
  import requests
58
 
59
- # Make a prediction
60
  response = requests.post(
61
- "https://huggingface.co/Jiahuita/NewsSourceClassification/predict",
62
  json={"text": "Your news headline here"}
63
  )
64
  print(response.json())
 
56
  ```python
57
  import requests
58
 
 
59
  response = requests.post(
60
+ "https://huggingface.co/Jiahuita/NewsSourceClassification",
61
  json={"text": "Your news headline here"}
62
  )
63
  print(response.json())
app.py DELETED
@@ -1,84 +0,0 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel
3
- from transformers import Pipeline
4
- import tensorflow as tf
5
- from tensorflow.keras.preprocessing.sequence import pad_sequences
6
- import json
7
- import os
8
-
9
- class TextInput(BaseModel):
10
- text: str
11
-
12
- app = FastAPI(
13
- title="News Source Classifier",
14
- description="A model to classify news headlines as either Fox News or NBC News",
15
- version="1.0.0"
16
- )
17
-
18
- class NewsClassificationPipeline(Pipeline):
19
- def __init__(self):
20
- super().__init__()
21
- model_path = os.path.join(os.path.dirname(__file__), 'news_classifier.h5')
22
- self.model = tf.keras.models.load_model(model_path)
23
-
24
- tokenizer_path = os.path.join(os.path.dirname(__file__), 'tokenizer.json')
25
- with open(tokenizer_path, 'r') as f:
26
- tokenizer_data = json.load(f)
27
- self.tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(tokenizer_data)
28
-
29
- def __call__(self, text):
30
- if isinstance(text, str):
31
- text = [text]
32
-
33
- sequences = self.tokenizer.texts_to_sequences(text)
34
- padded = pad_sequences(sequences, maxlen=128)
35
-
36
- predictions = self.model.predict(padded)
37
-
38
- results = []
39
- for pred in predictions:
40
- label = "foxnews" if pred[0] > 0.5 else "nbc"
41
- score = float(pred[0] if label == "foxnews" else 1 - pred[0])
42
- results.append({"label": label, "score": score})
43
-
44
- return results[0] if len(results) == 1 else results
45
-
46
- try:
47
- classifier = NewsClassificationPipeline()
48
- except Exception as e:
49
- print(f"Error initializing model: {str(e)}")
50
- raise
51
-
52
- @app.get("/")
53
- async def root():
54
- return {
55
- "message": "News Source Classification API",
56
- "usage": "Send POST request to /predict with {'text': 'your news headline'}"
57
- }
58
-
59
- @app.post("/predict")
60
- async def predict(input_data: TextInput):
61
- try:
62
- result = classifier(input_data.text)
63
- return result
64
- except Exception as e:
65
- raise HTTPException(status_code=500, detail=str(e))
66
-
67
- @app.get("/examples")
68
- async def examples():
69
- return {
70
- "examples": [
71
- {
72
- "title": "Crime News Headline",
73
- "text": "Wife of murdered Minnesota pastor hired 3 men to kill husband after affair: police"
74
- },
75
- {
76
- "title": "Science News Headline",
77
- "text": "Scientists discover breakthrough in renewable energy research"
78
- },
79
- {
80
- "title": "Political News Headline",
81
- "text": "Presidential candidates face off in heated debate over climate policies"
82
- }
83
- ]
84
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:459b49b28436622ac5c9f6e28171fb7d0acc9498e293876b5778846501c4ab94
3
- size 212
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae409354ee5a0f6edfd67b5b838c072be95c352a1e1faca73a2473ee8ac15253
3
+ size 286
pipeline.py CHANGED
@@ -1,35 +1,53 @@
1
- from transformers import Pipeline
2
- import tensorflow as tf
 
3
  from tensorflow.keras.preprocessing.sequence import pad_sequences
 
4
  import json
5
- import os
6
 
7
- def load_tokenizer(tokenizer_path):
8
- with open(tokenizer_path, 'r') as f:
9
- return json.load(f)
10
-
11
- class NewsClassificationPipeline(Pipeline):
12
- def __init__(self, model=None, tokenizer=None, **kwargs):
 
 
 
 
 
 
 
 
 
13
  super().__init__(**kwargs)
14
- model_path = os.path.join(os.path.dirname(__file__), './news_classifier.h5')
15
- self.model = tf.keras.models.load_model(model_path)
16
 
17
- tokenizer_path = os.path.join(os.path.dirname(__file__), './tokenizer.json')
18
- self.tokenizer_config = load_tokenizer(tokenizer_path)
19
-
20
- def __call__(self, texts, **kwargs):
21
- if isinstance(texts, str):
22
- texts = [texts]
23
 
24
- sequences = self.tokenizer.texts_to_sequences(texts)
25
- padded = pad_sequences(sequences, maxlen=128)
26
-
 
 
 
 
 
 
 
 
 
 
27
  predictions = self.model.predict(padded)
28
 
29
  results = []
30
  for pred in predictions:
31
  label = "foxnews" if pred[0] > 0.5 else "nbc"
32
  score = float(pred[0] if label == "foxnews" else 1 - pred[0])
33
- results.append({"label": label, "score": score})
34
-
35
- return results[0] if isinstance(texts, str) else results
 
 
 
 
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=128,
14
+ vocab_size=10000,
15
+ hidden_size=64,
16
+ num_labels=2,
17
+ **kwargs
18
+ ):
19
+ self.max_length = max_length
20
+ self.vocab_size = vocab_size
21
+ self.hidden_size = hidden_size
22
+ self.num_labels = num_labels
23
  super().__init__(**kwargs)
 
 
24
 
25
+ class NewsClassifier(PreTrainedModel):
26
+ config_class = NewsClassifierConfig
27
+ base_model_prefix = "news_classifier"
 
 
 
28
 
29
+ def __init__(self, config):
30
+ super().__init__(config)
31
+ self.model = load_model('news_classifier.h5')
32
+ with open('tokenizer.json', 'r') as f:
33
+ tokenizer_data = json.load(f)
34
+ self.tokenizer = tokenizer_from_json(tokenizer_data)
35
+
36
+ def forward(self, text_input):
37
+ if isinstance(text_input, str):
38
+ text_input = [text_input]
39
+
40
+ sequences = self.tokenizer.texts_to_sequences(text_input)
41
+ padded = pad_sequences(sequences, maxlen=self.config.max_length)
42
  predictions = self.model.predict(padded)
43
 
44
  results = []
45
  for pred in predictions:
46
  label = "foxnews" if pred[0] > 0.5 else "nbc"
47
  score = float(pred[0] if label == "foxnews" else 1 - pred[0])
48
+ results.append({
49
+ "label": label,
50
+ "score": score
51
+ })
52
+
53
+ return results[0] if len(text_input) == 1 else results