sailormars18 commited on
Commit
34bebfc
·
1 Parent(s): d272f5c

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -183
app.py DELETED
@@ -1,183 +0,0 @@
1
- # Python equivalent syntax of the Colab Notebook
2
-
3
- import subprocess
4
-
5
- subprocess.run(["pip", "install", "transformers", "torch", "gradio"])
6
-
7
- # Download and extract the Yelp review dataset
8
- import urllib.request
9
- import tarfile
10
-
11
- url = 'https://s3.amazonaws.com/fast-ai-nlp/yelp_review_polarity_csv.tgz'
12
- filename = 'yelp_review_polarity_csv.tgz'
13
-
14
- urllib.request.urlretrieve(url, filename)
15
-
16
- with tarfile.open(filename, 'r:gz') as tar:
17
- tar.extractall()
18
-
19
- import pandas as pd
20
-
21
- # Load training and testing datasets
22
- train_df = pd.read_csv('yelp_review_polarity_csv/train.csv', header=None, names=['label', 'text'])
23
- test_df = pd.read_csv('yelp_review_polarity_csv/test.csv', header=None, names=['label', 'text'])
24
-
25
- import re
26
-
27
- # Define a function for removing HTML tags, URLs, and extra spaces, and converting the text to lowercase
28
- def preprocess_text(text):
29
- # remove HTML tags
30
- text = re.sub('<[^<]+?>', '', text)
31
- # remove URLs
32
- text = re.sub(r'http\S+', '', text)
33
- # remove extra spaces
34
- text = re.sub(r' +', ' ', text)
35
- return text.strip().lower()
36
-
37
- # Apply the preprocessing function to the 'text' column of the training and test datasets
38
- train_df['text'] = train_df['text'].apply(preprocess_text)
39
- test_df['text'] = test_df['text'].apply(preprocess_text)
40
-
41
- import torch
42
- import transformers
43
- import gradio as gr
44
- from transformers import TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
45
-
46
- # Instantiate the tokenizer and the GPT-2 language model from the transformers library, and set the device to CUDA if available, otherwise to CPU
47
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
48
-
49
- tokenizer = transformers.GPT2Tokenizer.from_pretrained('gpt2')
50
- model = transformers.GPT2LMHeadModel.from_pretrained('gpt2').to(device)
51
-
52
- # Fine-tune the model on Yelp review dataset
53
- train_dataset = TextDataset(
54
- tokenizer=tokenizer,
55
- file_path='yelp_review_polarity_csv/train.csv',
56
- block_size=128,
57
- )
58
- test_dataset = TextDataset(
59
- tokenizer=tokenizer,
60
- file_path='yelp_review_polarity_csv/test.csv',
61
- block_size=128,
62
- )
63
- data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
64
-
65
- # Define the training arguments, instantiate the Trainer class from the transformers library, and train the model
66
- training_args = TrainingArguments(
67
- output_dir='./results',
68
- evaluation_strategy='steps',
69
- eval_steps=1000,
70
- save_steps=1000,
71
- save_total_limit=5,
72
- logging_steps=100,
73
- logging_dir='./logs',
74
- num_train_epochs=3,
75
- per_device_train_batch_size=16,
76
- per_device_eval_batch_size=32,
77
- learning_rate=1e-4,
78
- weight_decay=0.01,
79
- gradient_accumulation_steps=2,
80
- push_to_hub=False,
81
- max_steps=10000, # set a fixed number of training steps
82
- # save model checkpoints at specified intervals
83
- save_strategy="steps",
84
- )
85
-
86
- trainer = Trainer(
87
- model=model,
88
- args=training_args,
89
- train_dataset=train_dataset,
90
- data_collator=data_collator,
91
- eval_dataset=test_dataset,
92
- )
93
- trainer.train()
94
- trainer.save_model('./gpt2_yelp_review')
95
-
96
- # Evaluate the model on the test dataset and print the perplexity score
97
- eval_results = trainer.evaluate(eval_dataset=test_dataset)
98
- print(f"Perplexity: {eval_results['eval_loss']}")
99
-
100
- import pandas as pd
101
- import gradio as gr
102
- import re
103
- import torch
104
- import transformers
105
-
106
- # Define a function for generating text based on a prompt using the fine-tuned GPT-2 model and the tokenizer
107
- def generate_text(prompt, length=100, theme=None, **kwargs):
108
- model = transformers.GPT2LMHeadModel.from_pretrained('./gpt2_yelp_review').to(device)
109
- tokenizer = transformers.GPT2Tokenizer.from_pretrained('gpt2')
110
-
111
- # If a theme is specified, add it to the prompt as a prefix for a special token
112
- if theme:
113
- prompt = ' <{}> '.format(theme.strip()) + prompt.strip()
114
-
115
- input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
116
- attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device)
117
- pad_token_id = tokenizer.eos_token_id
118
-
119
- # Set the max length of the generated text based on the input parameter
120
- max_length = length if length > 0 else 100
121
-
122
- sample_outputs = model.generate(
123
- input_ids,
124
- attention_mask=attention_mask,
125
- pad_token_id=pad_token_id,
126
- do_sample=True,
127
- max_length=max_length,
128
- top_k=50,
129
- top_p=0.95,
130
- temperature=0.8,
131
- num_return_sequences=1,
132
- no_repeat_ngram_size=2,
133
- repetition_penalty=1.5,
134
- )
135
- generated_text = tokenizer.decode(sample_outputs[0], skip_special_tokens=True)
136
-
137
- # Post preprocessing of the generated text
138
-
139
- # Remove any leading and trailing quotation marks
140
- generated_text = generated_text.strip('"')
141
-
142
- # Remove leading and trailing whitespace
143
- generated_text = generated_text.strip()
144
-
145
- # Find the special token in the generated text and remove it
146
- match = re.search(r'<([^>]+)>', generated_text)
147
- if match:
148
- generated_text = generated_text[:match.start()] + generated_text[match.end():]
149
-
150
- # Remove any leading numeric characters and quotation marks
151
- generated_text = re.sub(r'^\d+', '', generated_text)
152
- generated_text = re.sub(r'^"', '', generated_text)
153
-
154
- # Remove any newline characters from the generated text
155
- generated_text = generated_text.replace('\n', '')
156
-
157
- # Remove any other unwanted special characters
158
- generated_text = re.sub(r'[^\w\s]+', '', generated_text)
159
-
160
- return generated_text.strip().capitalize()
161
-
162
- # Define a Gradio interface for the generate_text function, allowing users to input a prompt and generate text based on it
163
- iface = gr.Interface(
164
- fn=generate_text,
165
- inputs=['text', gr.inputs.Slider(minimum=10, maximum=100, default=50, label='Length of text'),
166
- gr.inputs.Textbox(default='Food', label='Theme')],
167
- outputs=[gr.outputs.Textbox(label='Generated Text')],
168
- title='Yelp Review Generator',
169
- description='Generate a Yelp review based on a prompt, length of text, and theme.',
170
- examples=[
171
- ['I had a great experience at this restaurant.', 50, 'Service'],
172
- ['The service was terrible and the food was cold.', 50, 'Atmosphere'],
173
- ['The food was delicious but the service was slow.', 50, 'Food'],
174
- ['The ambiance was amazing and the staff was friendly.', 75, 'Service'],
175
- ['The waitstaff was knowledgeable and attentive, but the noise level was a bit high.', 75, 'Atmosphere'],
176
- ['The menu had a good variety of options, but the portion sizes were a bit small for the price.', 75, 'Food']
177
- ],
178
- allow_flagging="manual",
179
- flagging_options=[("🙌", "positive"), ("😞", "negative")],
180
- )
181
-
182
- iface.launch(debug=False, share=True)
183
-