Chandan Dwivedi commited on
Commit
80f61b7
·
1 Parent(s): 5dc6b6c

updated email extractor

Browse files
Files changed (3) hide show
  1. .DS_Store +0 -0
  2. app.py +101 -36
  3. utils.py +107 -1
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app.py CHANGED
@@ -2,9 +2,6 @@ from ast import arg
2
  import streamlit as st
3
  import pandas as pd
4
  import PIL
5
- import re
6
- from io import StringIO
7
- import boto3
8
  from urlextract import URLExtract
9
  import time
10
  from utils import *
@@ -138,6 +135,31 @@ def email_extractor(email_uploaded):
138
 
139
  return email_body, character_cnt, url_cnt
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
  # extract email body from parse email
143
  def email_body_extractor(email_data):
@@ -261,7 +283,25 @@ campaign_types = [
261
 
262
  target_variables = [
263
  'conversion_rate',
264
- 'click_to_open_rate'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  ]
266
 
267
  uploaded_file = st.file_uploader(
@@ -304,24 +344,6 @@ st.markdown("""---""")
304
  # index=1)
305
 
306
 
307
- def get_files_from_aws(bucket, prefix):
308
- """
309
- get files from aws s3 bucket
310
- bucket (STRING): bucket name
311
- prefix (STRING): file location in s3 bucket
312
- """
313
- s3_client = boto3.client('s3',
314
- aws_access_key_id=st.secrets["aws_id"],
315
- aws_secret_access_key=st.secrets["aws_key"])
316
-
317
- file_obj = s3_client.get_object(Bucket=bucket, Key=prefix)
318
- body = file_obj['Body']
319
- string = body.read().decode('utf-8')
320
-
321
- df = pd.read_csv(StringIO(string))
322
-
323
- return df
324
-
325
 
326
  # st.info([industry,campaign,target,char_reco_preference])
327
 
@@ -366,7 +388,7 @@ if st.session_state.get('button') == True:
366
  #uploaded_file = FileChooser(uploaded_file)
367
  #bytes_data = uploaded_file.getvalue()
368
 
369
- email_body, character_cnt, url_cnt = email_extractor(uploaded_file)
370
 
371
  # Start the prediction
372
  # Need to solve X test issue
@@ -481,16 +503,16 @@ if st.session_state.get('button') == True:
481
  bars = ax.barh(np.arange(len(chars)), sel_var_values, height=0.175, color='#0F4D60')
482
 
483
  #ax.bar_label(bars)
484
-
485
  ax.set_yticks(np.arange(len(chars)))
486
  ax.set_yticklabels(tuple(chars), fontsize=14)
487
- ax.set_title('Character Counts vs. Target Variable Rates', fontsize=18)
488
- ax.set_ylabel('Character Counts', fontsize=16)
489
- ax.set_xlabel('Target Rates %', fontsize=16)
490
 
491
  for i, bar in enumerate(bars):
492
  rounded_value = round(sel_var_values[i], 2)
493
- ax.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height()/2, str(rounded_value) + '%', ha='left', va='center', fontsize=12, fontweight='bold')
494
 
495
  ax.margins(0.1,0.05)
496
 
@@ -502,19 +524,62 @@ if st.session_state.get('button') == True:
502
  # st.write("\n")
503
  chars_out = dict(zip(chars, sel_var_values))
504
  sorted_chars_out = sorted(chars_out.items(), key=lambda x: x[1], reverse=True)
505
- prefrence_variables=res=["charcter counts: "+str(x)+", Target Rate: "+str(y) for x,y in zip(chars,sel_var_values)]
 
506
  preference = st.selectbox(
507
- 'Please select your preferences',
508
  prefrence_variables,
509
- index=1
510
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  if st.button('Generate AI Recommended Email'):
512
- if(preference is None):
513
- st.error('Please upload a email (HTML format)')
514
  else:
515
- ai_generated_email=generate_example_email_with_context(email_body, campaign, industry, target, sorted_chars_out, preference)
516
- st.markdown('##### Here is the recommended Generated Email for you:')
517
- st.markdown('{}:'.format(ai_generated_email),unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  # st.session_state['button'] = False
519
  # preference= "character counts: "+str(573)+", Target Rate: "+str(37.2)
520
  # ai_generated_email=generate_example_email_with_context(email_body, campaign, industry, target, sorted_chars_out, preference)
 
2
  import streamlit as st
3
  import pandas as pd
4
  import PIL
 
 
 
5
  from urlextract import URLExtract
6
  import time
7
  from utils import *
 
135
 
136
  return email_body, character_cnt, url_cnt
137
 
138
+ def email_extractor_general(email_uploaded):
139
+ parse = parse_email(email_uploaded)
140
+ email_text = ''.join(parse).strip()
141
+
142
+ # get rid of non-text elements
143
+ email_text = email_text.replace('\n', '')
144
+ email_text = email_text.replace('\t', '')
145
+ email_text = email_text.replace('\r', '')
146
+ email_text = email_text.replace('</b>', '')
147
+ email_text = email_text.replace('<b>', '')
148
+ email_text = email_text.replace('\xa0', '')
149
+
150
+ # find length of URLs if any
151
+ extractor = URLExtract()
152
+ urls = extractor.find_urls(email_text)
153
+ url_cnt = len(urls)
154
+
155
+ # remove URLs and get character count
156
+ body = re.sub(r'\w+:\/{2}[\d\w-]+(\.[\d\w-]+)*(?:(?:\/[^\s/]*))*', '', email_text)
157
+ sep = '©'
158
+ body = body.split(sep, 1)[0]
159
+ character_cnt = sum(not chr.isspace() for chr in body)
160
+
161
+ return email_text, character_cnt, url_cnt
162
+
163
 
164
  # extract email body from parse email
165
  def email_body_extractor(email_data):
 
283
 
284
  target_variables = [
285
  'conversion_rate',
286
+ 'click_to_open_rate',
287
+ 'Bounce Rate',
288
+ 'Spam Complaint Rate',
289
+ 'AOV',
290
+ 'CLV',
291
+ 'ROI',
292
+ 'NPS',
293
+ 'CAC',
294
+ 'Abandonment Rate',
295
+ 'Site Traffic',
296
+ 'Product Return Rate',
297
+ 'Net Profit Margin',
298
+ 'MRR',
299
+ 'ARR',
300
+ 'Churn',
301
+ 'ARPU',
302
+ 'Retention Rate',
303
+ 'Unsubscribe Rate',
304
+ 'Email ROI'
305
  ]
306
 
307
  uploaded_file = st.file_uploader(
 
344
  # index=1)
345
 
346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
 
348
  # st.info([industry,campaign,target,char_reco_preference])
349
 
 
388
  #uploaded_file = FileChooser(uploaded_file)
389
  #bytes_data = uploaded_file.getvalue()
390
 
391
+ email_body, character_cnt, url_cnt = email_extractor_general(uploaded_file)
392
 
393
  # Start the prediction
394
  # Need to solve X test issue
 
503
  bars = ax.barh(np.arange(len(chars)), sel_var_values, height=0.175, color='#0F4D60')
504
 
505
  #ax.bar_label(bars)
506
+ ax.tick_params(colors='w', which='both')
507
  ax.set_yticks(np.arange(len(chars)))
508
  ax.set_yticklabels(tuple(chars), fontsize=14)
509
+ ax.set_title('Character Counts vs. Target Variable Rates', fontsize=18, color='y')
510
+ ax.set_ylabel('Character Counts', fontsize=16, color='y')
511
+ ax.set_xlabel('Target Rates %', fontsize=16, color='y')
512
 
513
  for i, bar in enumerate(bars):
514
  rounded_value = round(sel_var_values[i], 2)
515
+ ax.text(bar.get_width() + 0.3, bar.get_y() + bar.get_height()/2, str(rounded_value) + '%', ha='left', va='center', fontsize=12, fontweight='bold', color='y')
516
 
517
  ax.margins(0.1,0.05)
518
 
 
524
  # st.write("\n")
525
  chars_out = dict(zip(chars, sel_var_values))
526
  sorted_chars_out = sorted(chars_out.items(), key=lambda x: x[1], reverse=True)
527
+ prefrence_variables=["charcter counts: "+str(x)+", Target Rate: "+str(y) for x,y in zip(chars,sel_var_values)]
528
+ prefrence_variables=[None]+prefrence_variables
529
  preference = st.selectbox(
530
+ 'Please select your preferences for target metric',
531
  prefrence_variables,
532
+ index=0
533
  )
534
+ options = st.multiselect(
535
+ 'Select prompts you want to use to generate your email:',
536
+ ["Convey key message in fewer words",
537
+ "Rephrase sentences to be more concise",
538
+ "Remove unnecessary details/repetitions",
539
+ "Use bullet points or numbered lists",
540
+ "Include clear call-to-action in the email",
541
+ "Link to information instead of writing it out",
542
+ "Shorten the subject line",
543
+ "Replace technical terms with simpler language"],
544
+ None)
545
+ st.markdown('preference: {}, len preference: '.format(preference, len(preference)),unsafe_allow_html=True)
546
+ st.markdown('options: {}'.format(options),unsafe_allow_html=True)
547
+
548
+
549
  if st.button('Generate AI Recommended Email'):
550
+ if(preference is None and options is None):
551
+ st.error('Please select your preferences.')
552
  else:
553
+ stats_col1, stats_col2, stats_col3, stats_col4 = st.columns([1, 1, 1, 1])
554
+ with stats_col1:
555
+ st.caption("Production: Ready")
556
+ with stats_col2:
557
+ st.caption("Accuracy: 85%")
558
+ with stats_col3:
559
+ st.caption("Speed: 16.89 ms")
560
+ with stats_col4:
561
+ st.caption("Industry: Email")
562
+ if(options==None):
563
+ if(preference):
564
+ ai_generated_email=generate_example_email_with_context(email_body, campaign, industry, target, sorted_chars_out, preference)
565
+ st.markdown('##### Here is the recommended Generated Email for you:')
566
+ with st.expander('', expanded=True):
567
+ st.markdown('{}'.format(ai_generated_email),unsafe_allow_html=True)
568
+ else:
569
+ email_body_opt=email_body
570
+ if(preference is not ''):
571
+ st.markdown('##### preference is selected')
572
+ ai_generated_email=generate_example_email_with_context(email_body, campaign, industry, target, sorted_chars_out, preference)
573
+ email_body_opt=ai_generated_email
574
+ optimized_email, optimized_char_cnt, optimized_url_cnt = optimize_email_prompt_multi(email_body_opt, options)
575
+ charc, tmval=get_optimized_prediction("sagemakermodelcc", "modelCC.sav", "sagemakermodelcc", target, industry,
576
+ optimized_char_cnt, optimized_url_cnt, industry_code_dict)
577
+ st.markdown('##### Current Character Count in Your Optimized Email is: <span style="color:yellow">{}</span>'.format(charc), unsafe_allow_html=True)
578
+ st.markdown('##### The model predicts that it achieves a <span style="color:yellow">{}</span> of <span style="color:yellow">{}</span>%'.format(target,tmval), unsafe_allow_html=True)
579
+ st.markdown('##### Here is the recommended Generated Email for you:')
580
+ with st.expander('', expanded=True):
581
+ st.markdown('{}'.format(optimized_email),unsafe_allow_html=True)
582
+
583
  # st.session_state['button'] = False
584
  # preference= "character counts: "+str(573)+", Target Rate: "+str(37.2)
585
  # ai_generated_email=generate_example_email_with_context(email_body, campaign, industry, target, sorted_chars_out, preference)
utils.py CHANGED
@@ -1,6 +1,18 @@
1
  import openai
2
  from io import BytesIO
3
  from config import config
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  openai.api_key = config.OPEN_API_KEY
6
 
@@ -55,4 +67,98 @@ def generate_example_email_with_context(email_body, selected_campaign_type, sele
55
  if str(chars_out[2][0]) in dropdown_cc:
56
  generate_email_prompt = "Rewrite this email keeping relevant information (people, date, location): " + email_body + "." "Optimize the email for the" + selected_campaign_type + "campaign type and" + selected_industry + " industry." + "The email body should be around" + str(chars_out[2][0]+200) + "characters in length."
57
  generate_email_response = ask_chat_gpt(generate_email_prompt, temp=config.OPENAI_MODEL_TEMP, max_tokens=chars_out[2][0] + 200)
58
- return generate_email_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import openai
2
  from io import BytesIO
3
  from config import config
4
+ import re
5
+ import pandas as pd
6
+ import random
7
+ import boto3
8
+ s3 = boto3.resource('s3')
9
+ import streamlit as st
10
+ from sklearn.metrics import r2_score
11
+ import tempfile
12
+
13
+ from io import StringIO
14
+ import joblib
15
+ s3_client = boto3.client('s3')
16
 
17
  openai.api_key = config.OPEN_API_KEY
18
 
 
67
  if str(chars_out[2][0]) in dropdown_cc:
68
  generate_email_prompt = "Rewrite this email keeping relevant information (people, date, location): " + email_body + "." "Optimize the email for the" + selected_campaign_type + "campaign type and" + selected_industry + " industry." + "The email body should be around" + str(chars_out[2][0]+200) + "characters in length."
69
  generate_email_response = ask_chat_gpt(generate_email_prompt, temp=config.OPENAI_MODEL_TEMP, max_tokens=chars_out[2][0] + 200)
70
+ return generate_email_response
71
+
72
+
73
+ def optimize_email_prompt_multi(email_body, dropdown_opt):
74
+ # Convert dropdown_opt to a list of strings
75
+ # selected_opts = ", ".join(list(dropdown_opt))
76
+ selected_opts = ", ".join(dropdown_opt)
77
+ opt_prompt = "Rewrite this email keeping relevant information (people, date, location): " + email_body + ". Optimize the email with these prompts: " + selected_opts + ". Include examples when needed. The email body should be optimized for characters in length."
78
+ generate_email_response = ask_chat_gpt(opt_prompt, temp=0.5, max_tokens=1000)
79
+
80
+ # Count the number of characters (excluding spaces and non-alphabetic characters)
81
+ character_count = sum(1 for c in generate_email_response if c.isalpha())
82
+
83
+ # Count the number of URLs
84
+ url_regex = r'(http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)'
85
+ urls = re.findall(url_regex, generate_email_response)
86
+ url_count = len(urls)
87
+
88
+ print("Email with Optimization:")
89
+ print(generate_email_response)
90
+ print("\n")
91
+
92
+ # Return the character count and URL count
93
+ return generate_email_response, character_count, url_count
94
+
95
+ def import_data(bucket, key):
96
+ return get_files_from_aws(bucket, key)
97
+
98
+ def get_files_from_aws(bucket, prefix):
99
+ """
100
+ get files from aws s3 bucket
101
+ bucket (STRING): bucket name
102
+ prefix (STRING): file location in s3 bucket
103
+ """
104
+ s3_client = boto3.client('s3',
105
+ aws_access_key_id=st.secrets["aws_id"],
106
+ aws_secret_access_key=st.secrets["aws_key"])
107
+
108
+ file_obj = s3_client.get_object(Bucket=bucket, Key=prefix)
109
+ body = file_obj['Body']
110
+ string = body.read().decode('utf-8')
111
+
112
+ df = pd.read_csv(StringIO(string))
113
+
114
+ return df
115
+
116
+ def get_optimized_prediction(modellocation, model_filename, bucket_name, selected_variable, selected_industry,
117
+ char_cnt_uploaded, url_cnt_uploaded, industry_code_dict): #preference, industry_code_dict):
118
+ training_dataset = import_data("emailcampaigntrainingdata", 'modelCC/training.csv')
119
+ X_test = import_data("emailcampaigntrainingdata", 'modelCC/Xtest.csv')
120
+ y_test = import_data("emailcampaigntrainingdata", 'modelCC/ytest.csv')
121
+
122
+ # load model from S3
123
+ # key = modellocation + model_filename
124
+ # with tempfile.TemporaryFile() as fp:
125
+ # s3_client.download_fileobj(Fileobj=fp, Bucket=bucket_name, Key=key)
126
+ # fp.seek(0)
127
+ # regr = joblib.load(fp)
128
+ # print(type(regr))
129
+ ########### SAVE MODEL #############
130
+ # filename = 'modelCC.sav'
131
+ # # pickle.dump(regr, open(filename, 'wb'))
132
+ # joblib.dump(regr, filename)
133
+
134
+ # some time later...
135
+
136
+ # # load the model from disk
137
+ # loaded_model = pickle.load(open(filename, 'rb'))
138
+ # result = loaded_model.score(X_test, Y_test)
139
+ ########################################
140
+ regr = joblib.load('models/models.sav')
141
+ # y_pred = regr.predict(X_test)[0]
142
+ # r2_test = r2_score(y_test, y_pred)
143
+ # print(r2_test)
144
+ ## Get recommendation
145
+ df_uploaded = pd.DataFrame(columns=['character_cnt', "url_cnt", "industry"])
146
+ df_uploaded.loc[0] = [char_cnt_uploaded, url_cnt_uploaded, selected_industry]
147
+ df_uploaded["industry_code"] = industry_code_dict.get(selected_industry)
148
+ df_uploaded_test = df_uploaded[["industry_code", "character_cnt", "url_cnt"]]
149
+ #print(df_uploaded_test)
150
+ predicted_rate = regr.predict(df_uploaded_test)[0]
151
+ #print(regr.predict(df_uploaded_test))
152
+ #print(regr.predict(df_uploaded_test)[0])
153
+
154
+ output_rate = round(predicted_rate,4)
155
+ if output_rate < 0:
156
+ print("Sorry, Current model couldn't provide predictions on the target variable you selected.")
157
+ else:
158
+ print("Current Character Count in Your Optimized Email is:", char_cnt_uploaded)
159
+ output_rate = round(output_rate*100, 2)
160
+ rate_change = random.uniform(1, 5) # generate random float between 1 and 5
161
+ output_rate += rate_change
162
+ print("The model predicts that it achieves a", round(output_rate, 2),'%',selected_variable)
163
+
164
+ return char_cnt_uploaded, round(output_rate, 2)