nan-motherboard commited on
Commit
b619286
·
1 Parent(s): 1d139ed
Files changed (1) hide show
  1. utils.py +40 -0
utils.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
2
+ import re
3
+
4
+ # Load saved model and tokenizer
5
+ model_checkpoint = "24NLPGroupO/EmailGeneration"
6
+ tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, truncation=True)
7
+ model = AutoModelForCausalLM.from_pretrained(model_checkpoint)
8
+
9
+ # Set up the generation pipeline
10
+ generator = pipeline('text-generation', model=model, tokenizer=tokenizer)
11
+
12
+ def clean_generated_text(text):
13
+ # Basic cleaning
14
+ text = re.sub(r'^(Re:|Fwd:)', '', text) # Remove reply and forward marks
15
+ text = re.sub(r'Best regards,.*$', '', text, flags=re.DOTALL) # Remove everything after signature
16
+ text = re.sub(r'PHONE.*$', '', text, flags=re.DOTALL) # Remove everything after phone numbers
17
+ text = re.sub(r'Email:.*$', '', text, flags=re.DOTALL) # Remove everything after email addresses
18
+ text = re.sub(r'Cc:.*$', '', text, flags=re.DOTALL) # Remove CC list
19
+ text = re.sub(r'\* Attachments:.*', '', text, flags=re.S) # Remove 'Attachments:' and everything following it
20
+ text = re.sub(r'©️ .*$', '', text, flags=re.DOTALL) # Remove copyright and ownership statements
21
+ text = re.sub(r'URL If this message is not displaying properly, click here.*$', '', text, flags=re.DOTALL) # Remove error display message and links
22
+ text = re.sub(r'\d{5,}', 'NUMBER', text) # Replace long sequences of numbers, likely phone numbers or ZIP codes
23
+ return text.strip()
24
+
25
+ def generate_email(product, gender, profession, hobby):
26
+ input_text = f"{product} {gender} {profession} {hobby}"
27
+ result = generator(
28
+ input_text, # Initial text to prompt the model. Sets the context or topic for text generation.
29
+ max_length=256, # Maximum length of the generated text in tokens, limiting the output size.
30
+ do_sample=True, # Enables stochastic sampling; the model can generate diverse outputs at each step.
31
+ top_k=20, # Limits the vocabulary considered at each step to the top-k most likely next words.
32
+ top_p=0.6, # Uses nucleus sampling: Narrows down to the smallest set of words totaling 60% of the likelihood.
33
+ temperature=0.4, # Scales logits before sampling to reduce randomness and produce more deterministic output.
34
+ repetition_penalty=1.5, # Penalizes words that were already mentioned, reducing repetition in the text.
35
+ # truncation=True, # Truncates the output to the maximum length if it exceeds it.
36
+ num_return_sequences=3 # Generates three different sequences to choose from, enhancing output variety.
37
+ )
38
+ # Select the best output from the generated sequences
39
+ best_text = sorted([clean_generated_text(r['generated_text']) for r in result], key=len)[-1]
40
+ return best_text