Files changed (4) hide show
  1. SessionState.py +117 -0
  2. app.py +100 -57
  3. requirements.txt +0 -2
  4. utils.py +0 -51
SessionState.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Hack to add per-session state to Streamlit.
2
+
3
+ Usage
4
+ -----
5
+
6
+ >>> import SessionState
7
+ >>>
8
+ >>> session_state = SessionState.get(user_name='', favorite_color='black')
9
+ >>> session_state.user_name
10
+ ''
11
+ >>> session_state.user_name = 'Mary'
12
+ >>> session_state.favorite_color
13
+ 'black'
14
+
15
+ Since you set user_name above, next time your script runs this will be the
16
+ result:
17
+ >>> session_state = get(user_name='', favorite_color='black')
18
+ >>> session_state.user_name
19
+ 'Mary'
20
+
21
+ """
22
+ try:
23
+ import streamlit.ReportThread as ReportThread
24
+ from streamlit.server.Server import Server
25
+ except Exception:
26
+ # Streamlit >= 0.65.0
27
+ import streamlit.report_thread as ReportThread
28
+ from streamlit.server.server import Server
29
+
30
+
31
+ class SessionState(object):
32
+ def __init__(self, **kwargs):
33
+ """A new SessionState object.
34
+
35
+ Parameters
36
+ ----------
37
+ **kwargs : any
38
+ Default values for the session state.
39
+
40
+ Example
41
+ -------
42
+ >>> session_state = SessionState(user_name='', favorite_color='black')
43
+ >>> session_state.user_name = 'Mary'
44
+ ''
45
+ >>> session_state.favorite_color
46
+ 'black'
47
+
48
+ """
49
+ for key, val in kwargs.items():
50
+ setattr(self, key, val)
51
+
52
+
53
+ def get(**kwargs):
54
+ """Gets a SessionState object for the current session.
55
+
56
+ Creates a new object if necessary.
57
+
58
+ Parameters
59
+ ----------
60
+ **kwargs : any
61
+ Default values you want to add to the session state, if we're creating a
62
+ new one.
63
+
64
+ Example
65
+ -------
66
+ >>> session_state = get(user_name='', favorite_color='black')
67
+ >>> session_state.user_name
68
+ ''
69
+ >>> session_state.user_name = 'Mary'
70
+ >>> session_state.favorite_color
71
+ 'black'
72
+
73
+ Since you set user_name above, next time your script runs this will be the
74
+ result:
75
+ >>> session_state = get(user_name='', favorite_color='black')
76
+ >>> session_state.user_name
77
+ 'Mary'
78
+
79
+ """
80
+ # Hack to get the session object from Streamlit.
81
+
82
+ ctx = ReportThread.get_report_ctx()
83
+
84
+ this_session = None
85
+
86
+ current_server = Server.get_current()
87
+ if hasattr(current_server, '_session_infos'):
88
+ # Streamlit < 0.56
89
+ session_infos = Server.get_current()._session_infos.values()
90
+ else:
91
+ session_infos = Server.get_current()._session_info_by_id.values()
92
+
93
+ for session_info in session_infos:
94
+ s = session_info.session
95
+ if (
96
+ # Streamlit < 0.54.0
97
+ (hasattr(s, '_main_dg') and s._main_dg == ctx.main_dg)
98
+ or
99
+ # Streamlit >= 0.54.0
100
+ (not hasattr(s, '_main_dg') and s.enqueue == ctx.enqueue)
101
+ or
102
+ # Streamlit >= 0.65.2
103
+ (not hasattr(s, '_main_dg') and s._uploaded_file_mgr == ctx.uploaded_file_mgr)
104
+ ):
105
+ this_session = s
106
+
107
+ if this_session is None:
108
+ raise RuntimeError(
109
+ "Oh noes. Couldn't get your Streamlit Session object. "
110
+ 'Are you doing something fancy with threads?')
111
+
112
+ # Got the session object! Now let's attach some state into it.
113
+
114
+ if not hasattr(this_session, '_custom_session_state'):
115
+ this_session._custom_session_state = SessionState(**kwargs)
116
+
117
+ return this_session._custom_session_state
app.py CHANGED
@@ -1,58 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
- from utils import generate_email
3
-
4
-
5
- col1, col2=st.columns(2)
6
- with col1:
7
- with st.container(height=500):
8
- with st.form("my_input", clear_on_submit=True, border=False):
9
- st.write("Input")
10
- # product
11
- product=st.text_input("product", key="product")
12
- # gender
13
- gender=st.radio("gender", ["male", "female", "non-binary"], key="gender")
14
- # profession
15
- profession=st.text_input("profession", key="profession")
16
- # hobby
17
- hobby=st.text_input("hobby", key="hobby")
18
- # Every form must have a submit button.
19
- submitted = st.form_submit_button(label='Submit')
20
- # if submitted:
21
- # response = generate_email(st.session_state.product, st.session_state.gender, st.session_state.profession, st.session_state.hobby)
22
- # st.session_state.email=response
23
-
24
- with col2:
25
- if submitted:
26
- with st.spinner('Wait for it...'):
27
- response = generate_email(st.session_state.product, st.session_state.gender, st.session_state.profession, st.session_state.hobby)
28
- st.session_state.email=response
29
- print("st.session_state.email")
30
- print(st.session_state.email)
31
- with st.container(height=500):
32
- placeholder = st.empty()
33
- # Replace the chart with several elements:
34
- with placeholder.container():
35
- st.write("Product: " + st.session_state.product)
36
- st.write("Gender: " + st.session_state.gender)
37
- st.write("Profession: " + st.session_state.profession)
38
- st.write("Hobby: "+ st.session_state.hobby)
39
- st.write("Email: "+ st.session_state.email)
40
-
41
- if 'clicked' not in st.session_state:
42
- st.session_state.clicked = False
43
-
44
- def click_button():
45
- st.session_state.clicked = True
46
-
47
- st.button('Clear', on_click=click_button)
48
-
49
- if st.session_state.clicked:
50
- # The message and nested widget will remain on the page
51
- del st.session_state.product
52
- del st.session_state.gender
53
- del st.session_state.profession
54
- del st.session_state.hobby
55
- del st.session_state.email
56
- del st.session_state.clicked
57
- if submitted:
58
- placeholder.empty()
 
1
+ # import streamlit as st
2
+ # import time
3
+
4
+ # with st.form("my_input"):
5
+ # st.write("Input")
6
+ # # product
7
+ # product=st.text_input("product")
8
+ # # gender
9
+ # gender=st.radio("gender", ["male", "female"])
10
+ # # profession
11
+ # profession=st.text_input("profession")
12
+ # # hobby
13
+ # hobby=st.text_input("hobby")
14
+
15
+ # # Every form must have a submit button.
16
+ # col1, col2=st.columns(2)
17
+
18
+ # # Place a button in each column
19
+ # with col1:
20
+ # submitted = st.form_submit_button("Submit")
21
+
22
+ # with col2:
23
+ # clear = st.form_submit_button("Clear")
24
+
25
+
26
+
27
+ # with st.form("my_output"):
28
+ # if submitted:
29
+ # st.write("product", product)
30
+ # st.write("gender", gender)
31
+ # st.write("profession", profession)
32
+ # st.write("hobby", hobby)
33
+ # # Clear the user inputs
34
+ # if clear:
35
+ # st.experimental_rerun()
36
+
37
+ # _LOREM_IPSUM = """
38
+ # Lorem ipsum dolor sit amet, **consectetur adipiscing** elit, sed do eiusmod tempor
39
+ # incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
40
+ # nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
41
+ # """
42
+
43
+ # def stream_data():
44
+ # for word in _LOREM_IPSUM.split(" "):
45
+ # yield word + " "
46
+ # time.sleep(0.02)
47
+
48
+ # for word in _LOREM_IPSUM.split(" "):
49
+ # yield word + " "
50
+ # time.sleep(0.02)
51
+
52
+
53
+ # if st.button("Stream data"):
54
+ # st.write_stream(stream_data)
55
+
56
+
57
  import streamlit as st
58
+ import SessionState
59
+
60
+ # Initialize session state
61
+ session_state = SessionState.get(product="", gender="", profession="", hobby="")
62
+
63
+ # Create a form for user inputs
64
+ with st.form("my_input"):
65
+ st.write("Input")
66
+ # product
67
+ product = st.text_input("product", value=session_state.product)
68
+ # gender
69
+ gender = st.radio("gender", ["male", "female"], index=["male", "female"].index(session_state.gender) if session_state.gender else 0)
70
+ # profession
71
+ profession = st.text_input("profession", value=session_state.profession)
72
+ # hobby
73
+ hobby = st.text_input("hobby", value=session_state.hobby)
74
+
75
+ # Every form must have a submit button.
76
+ submitted = st.form_submit_button("Submit")
77
+ clear = st.form_submit_button("Clear")
78
+
79
+ # Display the user inputs
80
+ with st.form("my_output"):
81
+ if submitted and not clear:
82
+ # Save inputs to session state
83
+ session_state.product = product
84
+ session_state.gender = gender
85
+ session_state.profession = profession
86
+ session_state.hobby = hobby
87
+
88
+ st.write("product", product)
89
+ st.write("gender", gender)
90
+ st.write("profession", profession)
91
+ st.write("hobby", hobby)
92
+
93
+ # Clear the user inputs
94
+ if clear:
95
+ # Clear session state
96
+ session_state.product = ""
97
+ session_state.gender = ""
98
+ session_state.profession = ""
99
+ session_state.hobby = ""
100
+
101
+ st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt DELETED
@@ -1,2 +0,0 @@
1
- torch
2
- transformers>=4.24.0
 
 
 
utils.py DELETED
@@ -1,51 +0,0 @@
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 signature
16
- text = re.sub(r'PHONE.*$', '', text, flags=re.DOTALL) # Remove phone numbers
17
- text = re.sub(r'Email:.*$', '', text, flags=re.DOTALL) # Remove 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
20
- text = re.sub(r'©️ .*$', '', text, flags=re.DOTALL) # Remove copyright and ownership statements
21
- text = re.sub(r'URL', '', text) # Remove URLs
22
- text = re.sub(r'NUMBER', '10', text) # Replace 'NUMBER' with a real number
23
- text = re.sub(r'CURRENCYNUMBER', 'USD 100', text) # Replace 'CURRENCYNUMBER' with a real value
24
- text = re.sub(r'About Us.*', '', text, flags=re.DOTALL) # Remove 'About Us' and all following text
25
- text = re.sub(r'\d+ [^\s]+ St\.?,?.*?\d{5}', '', text) # Remove street
26
- text = re.sub(r'\d+ [^\s]+ Ave\.?,?.*?\d{5}', '', text) # Remove avenues
27
- text = re.sub(r'\d+ [^\s]+ Rd\.?,?.*?\d{5}', '', text) # Remove roads
28
- text = re.sub(r'\d+ [^\s]+ Ln\.?,?.*?\d{5}', '', text) # Remove lanes
29
- text = re.sub(r'\d+ [^\s]+ Blvd\.?,?.*?\d{5}', '', text) # Remove boulevards
30
- text = re.sub(r'\d+ [^\s]+ Dr\.?,?.*?\d{5}', '', text) # Remove drives
31
- text = re.sub(r'\d+ [^\s]+ Ct\.?,?.*?\d{5}', '', text) # Remove courts
32
- return text.strip()
33
-
34
- def generate_email(product, gender, profession, hobby):
35
- input_text = f"{product} {gender} {profession} {hobby}"
36
- result = generator(
37
- input_text, # The starting text that guides the model on what to generate
38
- max_length=256, # Set a suitable maximum length
39
- top_k=40, # Consider more top options words
40
- top_p=0.6, # Control the probability range for word choices
41
- temperature=0.4, # Control the randomness of generation
42
- repetition_penalty=1.5, # Reduce content repetition
43
- num_return_sequences=2, # Generate three texts
44
- do_sample=True
45
- )
46
- # Clean each generated text
47
- cleaned_texts = [clean_generated_text(seq['generated_text']) for seq in result]
48
- # Choose the best text based on length and clarity
49
- best_text = max(cleaned_texts, key=len)
50
- return best_text
51
-