Spaces:
Runtime error
Runtime error
robzchhangte
commited on
Commit
•
9be0e8c
1
Parent(s):
fc880ff
Upload 2 files
Browse files- app.py +43 -0
- requirements.txt +2 -0
app.py
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
# Load pre-trained GPT-2 model and tokenizer
|
6 |
+
model_name = "gpt2-large"
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
# Set pad token to eos token
|
9 |
+
tokenizer.pad_token = tokenizer.eos_token
|
10 |
+
model = AutoModelForCausalLM.from_pretrained(model_name)
|
11 |
+
|
12 |
+
|
13 |
+
def generate_text(input_text, max_length=32, num_beams=5, do_sample=False, no_repeat_ngram_size=2):
|
14 |
+
"""
|
15 |
+
Generate text based on the given input text.
|
16 |
+
Parameters:
|
17 |
+
- input_text (str): The input text to start generation from.
|
18 |
+
- max_length (int): Maximum length of the generated text.
|
19 |
+
- num_beams (int): Number of beams for beam search.
|
20 |
+
- do_sample (bool): Whether to use sampling or not.
|
21 |
+
- no_repeat_ngram_size (int): Size of the n-gram to avoid repetition.
|
22 |
+
Returns:
|
23 |
+
- generated_text (str): The generated text.
|
24 |
+
"""
|
25 |
+
# Encode the input text and move it to the appropriate device
|
26 |
+
input_ids = tokenizer(input_text, return_tensors='pt', padding=True)['input_ids']
|
27 |
+
# Generate text using the model
|
28 |
+
output = model.generate(input_ids, max_length=max_length, num_beams=num_beams,
|
29 |
+
do_sample=do_sample, no_repeat_ngram_size=no_repeat_ngram_size)
|
30 |
+
# Decode the generated output
|
31 |
+
generated_text = tokenizer.decode(output[0], skip_special_tokens=True)
|
32 |
+
return generated_text
|
33 |
+
|
34 |
+
|
35 |
+
# Create Gradio interface
|
36 |
+
input_text = gr.Textbox(lines=10, label="Input Text", placeholder="Enter text for text generation...")
|
37 |
+
output_text = gr.Textbox(label="Generated Text")
|
38 |
+
|
39 |
+
gr.Interface(generate_text, input_text, output_text,
|
40 |
+
title="Text Generation with GPT-2",
|
41 |
+
description="Generate text using the GPT-2 model.",
|
42 |
+
theme="default",
|
43 |
+
allow_flagging="never").launch()
|
requirements.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
transformers
|