Erfan11 commited on
Commit
29de403
1 Parent(s): c582cf1

Create text_generation.py

Browse files
Files changed (1) hide show
  1. text_generation.py +11 -0
text_generation.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
2
+
3
+ def generate_text(prompt, max_length=50):
4
+ model_name = "gpt2"
5
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
6
+ model = GPT2LMHeadModel.from_pretrained(model_name)
7
+
8
+ inputs = tokenizer.encode(prompt, return_tensors="pt")
9
+ outputs = model.generate(inputs, max_length=max_length, num_return_sequences=1)
10
+ text = tokenizer.decode(outputs[0], skip_special_tokens=True)
11
+ return text