faheem66 commited on
Commit
d101797
·
1 Parent(s): eb2d14a

changed training approach

Browse files
Files changed (1) hide show
  1. app.py +103 -42
app.py CHANGED
@@ -1,13 +1,15 @@
1
  import torch
2
  from torch.utils.data import Dataset, DataLoader
3
- from transformers import BertTokenizer, BertForSequenceClassification, AdamW
4
  from sklearn.model_selection import train_test_split
5
  import gradio as gr
6
  import random
7
  from faker import Faker
8
  import html
 
9
  import numpy as np
10
  from tqdm import tqdm
 
11
 
12
  # Constants
13
  MAX_LENGTH = 512
@@ -26,7 +28,7 @@ def generate_employee():
26
  return name, job, ext, email
27
 
28
 
29
- def generate_html_content(num_employees=9):
30
  employees = [generate_employee() for _ in range(num_employees)]
31
 
32
  html_content = f"""
@@ -38,26 +40,22 @@ def generate_html_content(num_employees=9):
38
  <div class="row ts-three-column-row standard-row">
39
  """
40
 
41
- for i, (name, job, ext, email) in enumerate(employees):
42
- if i % 3 == 0:
43
- html_content += '<div class="column ts-three-column">'
44
-
45
  html_content += f"""
46
- <div class="block">
47
- <div class="text-block" style="text-align: center;">
48
- <p>
49
- <strong>{html.escape(name)}</strong><br>
50
- <span style="font-size: 16px">{html.escape(job)}</span><br>
51
- <span style="font-size: 16px">{html.escape(ext)}</span><br>
52
- <a href="mailto:{html.escape(email)}">Send Email</a>
53
- </p>
 
 
54
  </div>
55
  </div>
56
  """
57
 
58
- if (i + 1) % 3 == 0 or i == len(employees) - 1:
59
- html_content += '</div>'
60
-
61
  html_content += """
62
  </div>
63
  </body>
@@ -80,6 +78,8 @@ class HTMLDataset(Dataset):
80
  self.data = data
81
  self.tokenizer = tokenizer
82
  self.max_length = max_length
 
 
83
 
84
  def __len__(self):
85
  return len(self.data)
@@ -90,22 +90,38 @@ class HTMLDataset(Dataset):
90
  html,
91
  add_special_tokens=True,
92
  max_length=self.max_length,
93
- return_token_type_ids=False,
94
  padding='max_length',
95
  truncation=True,
96
  return_attention_mask=True,
97
  return_tensors='pt',
98
  )
99
 
100
- # Create a binary classification task: 1 if there are employees, 0 otherwise
101
- label = 1 if employees else 0
102
 
103
  return {
104
  'input_ids': encoding['input_ids'].flatten(),
105
  'attention_mask': encoding['attention_mask'].flatten(),
106
- 'labels': torch.tensor(label, dtype=torch.float)
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
  def train_model():
111
  # Generate synthetic dataset
@@ -114,7 +130,7 @@ def train_model():
114
 
115
  # Initialize tokenizer and model
116
  tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
117
- model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=1)
118
 
119
  # Prepare datasets and dataloaders
120
  train_dataset = HTMLDataset(train_data, tokenizer, MAX_LENGTH)
@@ -171,7 +187,6 @@ def extract_content(html, model, tokenizer):
171
  html,
172
  add_special_tokens=True,
173
  max_length=MAX_LENGTH,
174
- return_token_type_ids=False,
175
  padding='max_length',
176
  truncation=True,
177
  return_attention_mask=True,
@@ -183,16 +198,50 @@ def extract_content(html, model, tokenizer):
183
 
184
  with torch.no_grad():
185
  outputs = model(input_ids, attention_mask=attention_mask)
186
- predictions = outputs.logits.sigmoid().cpu().numpy()
187
-
188
- # Extract content based on predictions
189
- confidence = predictions[0][0]
190
- if confidence > 0.5:
191
- extracted_content = "Employee information detected"
192
- else:
193
- extracted_content = "No employee information detected"
194
-
195
- return f"{extracted_content} (confidence: {confidence:.2f})"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
 
198
  def test_model(html_input, model, tokenizer):
@@ -201,18 +250,30 @@ def test_model(html_input, model, tokenizer):
201
 
202
 
203
  def gradio_interface(html_input, test_type):
204
- global trained_model, trained_tokenizer
205
  if test_type == "Custom Input":
206
- return test_model(html_input, trained_model, trained_tokenizer)
 
207
  elif test_type == "Generate Random HTML":
208
  random_html, _ = generate_html_content()
209
- result = test_model(random_html, trained_model, trained_tokenizer)
210
  return random_html, result
211
 
212
 
213
- print("Starting training process...")
214
- trained_model, trained_tokenizer = train_model()
215
- print("Training completed. Launching Gradio interface...")
 
 
 
 
 
 
 
 
 
 
 
216
 
217
  iface = gr.Interface(
218
  fn=gradio_interface,
@@ -222,10 +283,10 @@ iface = gr.Interface(
222
  ],
223
  outputs=[
224
  gr.Textbox(lines=10, label="HTML Content"),
225
- gr.Textbox(label="Extracted Information")
226
  ],
227
  title="HTML Content Extractor",
228
- description="Enter HTML content or generate random HTML to test the model."
229
  )
230
 
231
- iface.launch()
 
1
  import torch
2
  from torch.utils.data import Dataset, DataLoader
3
+ from transformers import BertTokenizer, BertForTokenClassification, AdamW
4
  from sklearn.model_selection import train_test_split
5
  import gradio as gr
6
  import random
7
  from faker import Faker
8
  import html
9
+ import json
10
  import numpy as np
11
  from tqdm import tqdm
12
+ import os
13
 
14
  # Constants
15
  MAX_LENGTH = 512
 
28
  return name, job, ext, email
29
 
30
 
31
+ def generate_html_content(num_employees=3):
32
  employees = [generate_employee() for _ in range(num_employees)]
33
 
34
  html_content = f"""
 
40
  <div class="row ts-three-column-row standard-row">
41
  """
42
 
43
+ for name, job, ext, email in employees:
 
 
 
44
  html_content += f"""
45
+ <div class="column ts-three-column">
46
+ <div class="block">
47
+ <div class="text-block" style="text-align: center;">
48
+ <p>
49
+ <strong>{html.escape(name)}</strong><br>
50
+ <span style="font-size: 16px">{html.escape(job)}</span><br>
51
+ <span style="font-size: 16px">{html.escape(ext)}</span><br>
52
+ <a href="mailto:{html.escape(email)}">Send Email</a>
53
+ </p>
54
+ </div>
55
  </div>
56
  </div>
57
  """
58
 
 
 
 
59
  html_content += """
60
  </div>
61
  </body>
 
78
  self.data = data
79
  self.tokenizer = tokenizer
80
  self.max_length = max_length
81
+ self.label_map = {"O": 0, "B-NAME": 1, "I-NAME": 2, "B-JOB": 3, "I-JOB": 4, "B-EXT": 5, "I-EXT": 6,
82
+ "B-EMAIL": 7, "I-EMAIL": 8}
83
 
84
  def __len__(self):
85
  return len(self.data)
 
90
  html,
91
  add_special_tokens=True,
92
  max_length=self.max_length,
 
93
  padding='max_length',
94
  truncation=True,
95
  return_attention_mask=True,
96
  return_tensors='pt',
97
  )
98
 
99
+ labels = self.create_labels(encoding['input_ids'][0], employees)
 
100
 
101
  return {
102
  'input_ids': encoding['input_ids'].flatten(),
103
  'attention_mask': encoding['attention_mask'].flatten(),
104
+ 'labels': torch.tensor(labels, dtype=torch.long)
105
  }
106
 
107
+ def create_labels(self, tokens, employees):
108
+ labels = [0] * len(tokens) # Initialize all labels as "O"
109
+ for name, job, ext, email in employees:
110
+ self.label_sequence(tokens, name, "NAME", labels)
111
+ self.label_sequence(tokens, job, "JOB", labels)
112
+ self.label_sequence(tokens, ext, "EXT", labels)
113
+ self.label_sequence(tokens, email, "EMAIL", labels)
114
+ return labels
115
+
116
+ def label_sequence(self, tokens, text, label_type, labels):
117
+ text_tokens = self.tokenizer.encode(text, add_special_tokens=False)
118
+ for i in range(len(tokens) - len(text_tokens) + 1):
119
+ if tokens[i:i + len(text_tokens)] == text_tokens:
120
+ labels[i] = self.label_map[f"B-{label_type}"]
121
+ for j in range(1, len(text_tokens)):
122
+ labels[i + j] = self.label_map[f"I-{label_type}"]
123
+ break
124
+
125
 
126
  def train_model():
127
  # Generate synthetic dataset
 
130
 
131
  # Initialize tokenizer and model
132
  tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
133
+ model = BertForTokenClassification.from_pretrained('bert-base-uncased', num_labels=9)
134
 
135
  # Prepare datasets and dataloaders
136
  train_dataset = HTMLDataset(train_data, tokenizer, MAX_LENGTH)
 
187
  html,
188
  add_special_tokens=True,
189
  max_length=MAX_LENGTH,
 
190
  padding='max_length',
191
  truncation=True,
192
  return_attention_mask=True,
 
198
 
199
  with torch.no_grad():
200
  outputs = model(input_ids, attention_mask=attention_mask)
201
+ predictions = outputs.logits.argmax(dim=2)
202
+
203
+ tokens = tokenizer.convert_ids_to_tokens(input_ids[0])
204
+ label_map = {0: "O", 1: "B-NAME", 2: "I-NAME", 3: "B-JOB", 4: "I-JOB", 5: "B-EXT", 6: "I-EXT", 7: "B-EMAIL",
205
+ 8: "I-EMAIL"}
206
+
207
+ extracted_info = []
208
+ current_entity = {"type": None, "value": ""}
209
+
210
+ for token, prediction in zip(tokens, predictions[0]):
211
+ if token == "[PAD]":
212
+ break
213
+
214
+ label = label_map[prediction.item()]
215
+ if label.startswith("B-"):
216
+ if current_entity["type"]:
217
+ extracted_info.append(current_entity)
218
+ current_entity = {"type": label[2:], "value": token}
219
+ elif label.startswith("I-"):
220
+ if current_entity["type"] == label[2:]:
221
+ current_entity["value"] += " " + token
222
+ elif label == "O":
223
+ if current_entity["type"]:
224
+ extracted_info.append(current_entity)
225
+ current_entity = {"type": None, "value": ""}
226
+
227
+ if current_entity["type"]:
228
+ extracted_info.append(current_entity)
229
+
230
+ # Group entities by employee
231
+ employees = []
232
+ current_employee = {}
233
+ for entity in extracted_info:
234
+ if entity["type"] == "NAME":
235
+ if current_employee:
236
+ employees.append(current_employee)
237
+ current_employee = {"name": entity["value"]}
238
+ else:
239
+ current_employee[entity["type"].lower()] = entity["value"]
240
+
241
+ if current_employee:
242
+ employees.append(current_employee)
243
+
244
+ return json.dumps(employees, indent=2)
245
 
246
 
247
  def test_model(html_input, model, tokenizer):
 
250
 
251
 
252
  def gradio_interface(html_input, test_type):
253
+ global model, tokenizer
254
  if test_type == "Custom Input":
255
+ result = test_model(html_input, model, tokenizer)
256
+ return html_input, result
257
  elif test_type == "Generate Random HTML":
258
  random_html, _ = generate_html_content()
259
+ result = test_model(random_html, model, tokenizer)
260
  return random_html, result
261
 
262
 
263
+ # Check if the model is already trained and saved
264
+ if os.path.exists('model.pth') and os.path.exists('tokenizer'):
265
+ print("Loading pre-trained model...")
266
+ model = BertForTokenClassification.from_pretrained('bert-base-uncased', num_labels=9)
267
+ model.load_state_dict(torch.load('model.pth'))
268
+ tokenizer = BertTokenizer.from_pretrained('tokenizer')
269
+ else:
270
+ print("Training new model...")
271
+ model, tokenizer = train_model()
272
+ # Save the model and tokenizer
273
+ torch.save(model.state_dict(), 'model.pth')
274
+ tokenizer.save_pretrained('tokenizer')
275
+
276
+ print("Launching Gradio interface...")
277
 
278
  iface = gr.Interface(
279
  fn=gradio_interface,
 
283
  ],
284
  outputs=[
285
  gr.Textbox(lines=10, label="HTML Content"),
286
+ gr.Textbox(label="Extracted Information (JSON)")
287
  ],
288
  title="HTML Content Extractor",
289
+ description="Enter HTML content or generate random HTML to test the model. The model will extract employee information and return it in JSON format."
290
  )
291
 
292
+ iface.launch(share=True)