sailormars18 commited on
Commit
0bdfa16
·
1 Parent(s): 4b3d2bd

Delete app.py

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