Spaces:
Sleeping
Sleeping
Create text_generation.py
Browse files- 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
|