-
Notifications
You must be signed in to change notification settings - Fork 1
/
classify_clickbait_DBERT.py
66 lines (44 loc) · 1.85 KB
/
classify_clickbait_DBERT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from transformers import AutoTokenizer, AutoModelForSequenceClassification, pipeline
import os
import json
# Function to read JSON files
def load_json_file(filename):
with open(filename, "r") as file_read:
return json.load(file_read)
# Function to write JSON files
def write_json(filename, dict_to_print):
with open(filename, "w") as file_write:
return file_write.write(json.dumps(dict_to_print, indent=4))
# Load the tokenizer and the model
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
model = AutoModelForSequenceClassification.from_pretrained("models/predict")
MAX_LENGTH = 20
# File to keep record of the classified files
classifiedFile = f"classification/memory/classified_phrases_prob_{MAX_LENGTH}.json"
classifiedPhrases = []
if os.path.exists(classifiedFile):
classifiedPhrases = load_json_file(classifiedFile)
# File to keep record of all the labels for the phrases
labelsFile = f"classification/results/labels_{MAX_LENGTH}.json"
labels = []
if os.path.exists(labelsFile):
labels = load_json_file(labelsFile)
# Create the classifier
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
# Directory of the phrases
phrasesDirectory = f"output_phrases/{MAX_LENGTH}"
for file in os.listdir(phrasesDirectory):
if file not in classifiedPhrases:
file_location = phrasesDirectory+"/"+file
sentences = load_json_file(file_location)
# Analyze if the phrase is clickbait
for sentence in sentences:
result = classifier(sentence)
label = 1
if "0" in result["label"]:
label = 0
labels.append(label)
# Write the results and that the file has been analyzed
classifiedPhrases.append(file)
write_json(classifiedFile, classifiedPhrases)
write_json(labelsFile, labels)