-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathAI Blog Writter Using Hugging Face Transformers & GPT-2.py
More file actions
67 lines (42 loc) · 1.19 KB
/
Copy pathAI Blog Writter Using Hugging Face Transformers & GPT-2.py
File metadata and controls
67 lines (42 loc) · 1.19 KB
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
# To add a new cell, type '# %%'
# To add a new markdown cell, type '# %% [markdown]'
# %% [markdown]
# ### Import dependencies
# %%
from transformers import GPT2LMHeadModel , GPT2Tokenizer
# %% [markdown]
# ### Load Model
# %%
tokenizer = GPT2Tokenizer.from_pretrained('gpt2-large')
model = GPT2LMHeadModel.from_pretrained('gpt2-large' , pad_token_id = tokenizer.eos_token_id )
# %%
tokenizer.decode(tokenizer.eos_token_id)
# %% [markdown]
# ### Tokenize the text
# %%
sentence = "Love is"
input_ids = tokenizer.encode(sentence , return_tensors = 'pt')
# %%
input_ids
# %%
tokenizer.decode(input_ids[0])
# %%
print(tokenizer.decode(input_ids[0][1]))
print(tokenizer.decode(input_ids[0][2]))
print(tokenizer.decode(input_ids[0][3]))
print(tokenizer.decode(input_ids[0][4]))
# %% [markdown]
# ### Generate and Decode Text
# %%
output = model.generate(input_ids, max_length = 500, num_beams = 5,no_repeat_ngram_size = 2 , early_stopping = True)
# %%
output[0]
# %%
print(tokenizer.decode(output[0] , skip_special_tokens = True))
# %% [markdown]
# ### Output Result
# %%
text = tokenizer.decode(output[0] , skip_special_tokens = True)
# %%
with open('blog_ai.txt','w') as f:
f.write(text)