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

Upload nlpapp_4900.py

Browse files
Files changed (1) hide show
  1. nlpapp_4900.py +216 -0
nlpapp_4900.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """nlpapp_4900.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1QE4TN1ipB5SwIVy2a7D6_bTPujHMBoDu
8
+ """
9
+
10
+ # Import required modules for auto-reconnecting to the Colab runtime
11
+ # Set up auto-reconnect
12
+ import IPython
13
+ from google.colab import output
14
+
15
+ # Configure the JS code to automatically reconnect
16
+ def restart_runtime():
17
+ output.clear()
18
+ print('Restarting runtime...')
19
+ display(IPython.display.Javascript('''
20
+ const outputArea = this;
21
+ const kernel = IPython.notebook.kernel;
22
+ const command = 'notebook_utils.restart_runtime()';
23
+ kernel.execute(command).then(() => {
24
+ outputArea.clear_output();
25
+ console.log('Runtime restarted. Running all cells...');
26
+ IPython.notebook.execute_all_cells();
27
+ });
28
+ '''))
29
+
30
+ # Set the number of minutes of inactivity before auto-reconnecting
31
+
32
+ minutes = 30 #@param {type: "slider", min: 1, max: 180, step: 1} # define a slider widget to set the time before auto-reconnecting
33
+
34
+ # Register the auto-reconnect function
35
+ import time
36
+ def auto_reconnect():
37
+ while True:
38
+ print(f'Auto-reconnect in {minutes} minute(s)...')
39
+ time.sleep(minutes * 60 - 5) # Subtract 5 seconds to give the reconnect JS code time to run
40
+ restart_runtime()
41
+
42
+ # Start the auto-reconnect loop in the background
43
+ import threading
44
+ auto_reconnect_thread = threading.Thread(target=auto_reconnect)
45
+ auto_reconnect_thread.start()
46
+
47
+ !pip install transformers torch gradio
48
+
49
+ # Download and extract the Yelp review dataset: download and extract the dataset using wget and tar
50
+ !wget https://s3.amazonaws.com/fast-ai-nlp/yelp_review_polarity_csv.tgz
51
+ !tar -xvzf yelp_review_polarity_csv.tgz
52
+
53
+ import pandas as pd
54
+
55
+ train_df = pd.read_csv('yelp_review_polarity_csv/train.csv', header=None, names=['label', 'text'])
56
+ test_df = pd.read_csv('yelp_review_polarity_csv/test.csv', header=None, names=['label', 'text'])
57
+
58
+ import re
59
+
60
+ # Define a function for removing HTML tags, URLs, and extra spaces, and converting the text to lowercase
61
+ def preprocess_text(text):
62
+ # remove HTML tags
63
+ text = re.sub('<[^<]+?>', '', text)
64
+ # remove URLs
65
+ text = re.sub(r'http\S+', '', text)
66
+ # remove extra spaces
67
+ text = re.sub(r' +', ' ', text)
68
+ return text.strip().lower()
69
+
70
+ # Apply the preprocessing function to the 'text' column of the training and test datasets
71
+ train_df['text'] = train_df['text'].apply(preprocess_text)
72
+ test_df['text'] = test_df['text'].apply(preprocess_text)
73
+
74
+ import torch
75
+ import transformers
76
+ import gradio as gr
77
+ from transformers import TextDataset, DataCollatorForLanguageModeling, Trainer, TrainingArguments
78
+
79
+ # Instantiate the tokenizer and the GPT-2 language model from the transformers library, and set the device to CUDA if available, otherwise to CPU
80
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
81
+
82
+ tokenizer = transformers.GPT2Tokenizer.from_pretrained('gpt2')
83
+ model = transformers.GPT2LMHeadModel.from_pretrained('gpt2').to(device)
84
+
85
+ # Fine-tune the model on Yelp review dataset
86
+ train_dataset = TextDataset(
87
+ tokenizer=tokenizer,
88
+ file_path='yelp_review_polarity_csv/train.csv',
89
+ block_size=128,
90
+ )
91
+ test_dataset = TextDataset(
92
+ tokenizer=tokenizer,
93
+ file_path='yelp_review_polarity_csv/test.csv',
94
+ block_size=128,
95
+ )
96
+ data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)
97
+
98
+ # Define the training arguments, instantiate the Trainer class from the transformers library, and train the model
99
+ training_args = TrainingArguments(
100
+ output_dir='./results',
101
+ evaluation_strategy='steps',
102
+ eval_steps=1000,
103
+ save_steps=1000,
104
+ save_total_limit=5,
105
+ logging_steps=100,
106
+ logging_dir='./logs',
107
+ num_train_epochs=3,
108
+ per_device_train_batch_size=16,
109
+ per_device_eval_batch_size=32,
110
+ learning_rate=1e-4,
111
+ weight_decay=0.01,
112
+ gradient_accumulation_steps=2,
113
+ push_to_hub=False,
114
+ max_steps=10000, # set a fixed number of training steps
115
+ # save model checkpoints at specified intervals
116
+ save_strategy="steps",
117
+ )
118
+
119
+ trainer = Trainer(
120
+ model=model,
121
+ args=training_args,
122
+ train_dataset=train_dataset,
123
+ data_collator=data_collator,
124
+ eval_dataset=test_dataset,
125
+ )
126
+ trainer.train()
127
+ trainer.save_model('./gpt2_yelp_review')
128
+
129
+ # Evaluate the model on the test dataset and print the perplexity score
130
+ eval_results = trainer.evaluate(eval_dataset=test_dataset)
131
+ print(f"Perplexity: {eval_results['eval_loss']}")
132
+
133
+ import pandas as pd
134
+ import gradio as gr
135
+ import re
136
+ import torch
137
+ import transformers
138
+
139
+ # Define a function for generating text based on a prompt using the fine-tuned GPT-2 model and the tokenizer
140
+ def generate_text(prompt, length=100, theme=None, **kwargs):
141
+ model = transformers.GPT2LMHeadModel.from_pretrained('./gpt2_yelp_review').to(device)
142
+ tokenizer = transformers.GPT2Tokenizer.from_pretrained('gpt2')
143
+
144
+ # If a theme is specified, add it to the prompt as a prefix for a special token
145
+ if theme:
146
+ prompt = ' <{}> '.format(theme.strip()) + prompt.strip()
147
+
148
+ input_ids = tokenizer.encode(prompt, return_tensors='pt').to(device)
149
+ attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=device)
150
+ pad_token_id = tokenizer.eos_token_id
151
+
152
+ # Set the max length of the generated text based on the input parameter
153
+ max_length = length if length > 0 else 100
154
+
155
+ sample_outputs = model.generate(
156
+ input_ids,
157
+ attention_mask=attention_mask,
158
+ pad_token_id=pad_token_id,
159
+ do_sample=True,
160
+ max_length=max_length,
161
+ top_k=50,
162
+ top_p=0.95,
163
+ temperature=0.8,
164
+ num_return_sequences=1,
165
+ no_repeat_ngram_size=2,
166
+ repetition_penalty=1.5,
167
+ )
168
+ generated_text = tokenizer.decode(sample_outputs[0], skip_special_tokens=True)
169
+
170
+ # Post preprocessing of the generated text
171
+
172
+ # Remove any leading and trailing quotation marks
173
+ generated_text = generated_text.strip('"')
174
+
175
+ # Remove leading and trailing whitespace
176
+ generated_text = generated_text.strip()
177
+
178
+ # Find the special token in the generated text and remove it
179
+ match = re.search(r'<([^>]+)>', generated_text)
180
+ if match:
181
+ generated_text = generated_text[:match.start()] + generated_text[match.end():]
182
+
183
+ # Remove any leading numeric characters and quotation marks
184
+ generated_text = re.sub(r'^\d+', '', generated_text)
185
+ generated_text = re.sub(r'^"', '', generated_text)
186
+
187
+ # Remove any newline characters from the generated text
188
+ generated_text = generated_text.replace('\n', '')
189
+
190
+ # Remove any other unwanted special characters
191
+ generated_text = re.sub(r'[^\w\s]+', '', generated_text)
192
+
193
+ return generated_text.strip().capitalize()
194
+
195
+ # Define a Gradio interface for the generate_text function, allowing users to input a prompt and generate text based on it
196
+ iface = gr.Interface(
197
+ fn=generate_text,
198
+ inputs=['text', gr.inputs.Slider(minimum=10, maximum=100, default=50, label='Length of text'),
199
+ gr.inputs.Textbox(default='Food', label='Theme')],
200
+ outputs=[gr.outputs.Textbox(label='Generated Text')],
201
+ title='Yelp Review Generator',
202
+ description='Generate a Yelp review based on a prompt, length of text, and theme.',
203
+ examples=[
204
+ ['I had a great experience at this restaurant.', 50, 'Service'],
205
+ ['The service was terrible and the food was cold.', 50, 'Atmosphere'],
206
+ ['The food was delicious but the service was slow.', 50, 'Food'],
207
+ ['The ambiance was amazing and the staff was friendly.', 75, 'Service'],
208
+ ['The waitstaff was knowledgeable and attentive, but the noise level was a bit high.', 75, 'Atmosphere'],
209
+ ['The menu had a good variety of options, but the portion sizes were a bit small for the price.', 75, 'Food']
210
+ ],
211
+ allow_flagging="manual",
212
+ flagging_options=[("🙌", "positive"), ("😞", "negative")],
213
+ )
214
+
215
+ iface.launch(debug=False, share=True)
216
+