Ronio Jerico Roque commited on
Commit
540bd44
Β·
1 Parent(s): daa41ad

Refactor upload handling in client_summary and sem_ppc classes for improved user feedback and session state management

Browse files
Files changed (3) hide show
  1. classes/client_summary.py +33 -73
  2. classes/sem_ppc.py +136 -81
  3. pages/home.py +16 -21
classes/client_summary.py CHANGED
@@ -1,35 +1,10 @@
1
  import streamlit as st
2
- import threading
3
  from dotenv import load_dotenv
4
  from helper.telemetry import collect_telemetry
5
  from helper.upload_File import uploadFile
6
  from helper.button_behaviour import hide_button
 
7
 
8
- class ThreadSafeHandler:
9
- def __init__(self, placeholder):
10
- self.placeholder = placeholder
11
- self.lock = threading.Lock()
12
-
13
- def update_info(self, message):
14
- with self.lock:
15
- try:
16
- self.placeholder.info(message)
17
- except Exception:
18
- pass
19
-
20
- def update_success(self, message):
21
- with self.lock:
22
- try:
23
- self.placeholder.success(message)
24
- except Exception:
25
- pass
26
-
27
- def update_error(self, message):
28
- with self.lock:
29
- try:
30
- self.placeholder.error(message)
31
- except Exception:
32
- pass
33
 
34
  class CientSummary:
35
  def __init__(self):
@@ -48,58 +23,43 @@ class CientSummary:
48
  if 'target_market' not in st.session_state:
49
  st.session_state['target_market'] = ''
50
 
51
- def process(self):
52
- session = st.session_state.analyze
53
- if (self.client_summary or self.name or self.website) and session == 'clicked':
54
- try:
55
- # Prepare client data
56
- client_data = {
57
- 'client_summary': self.client_summary,
58
- 'client_name': self.name,
59
- 'client_website': self.website
60
- }
61
-
62
- # Placeholder to display feedback
63
- handler = ThreadSafeHandler(st.empty())
64
 
65
- def upload_client_data(field_key, field_value):
66
- try:
67
- handler.update_info(f"Uploading {field_key.replace('_', ' ').title()}...")
68
- # Simulate the processing logic here
69
- st.session_state[field_key] = 'uploaded' # Mock upload success
70
- collect_telemetry({'data_field': field_key.replace('_', ' ').title(), 'result': field_value})
71
- handler.update_success(f"{field_key.replace('_', ' ').title()} uploaded.")
72
- except Exception as e:
73
- handler.update_error(f"Error uploading {field_key.replace('_', ' ').title()}: {e}")
74
-
75
- # Start threads for each client field
76
- threads = []
77
- for field_key, field_value in client_data.items():
78
- thread = threading.Thread(target=upload_client_data, args=(field_key, field_value))
79
- thread.start()
80
- threads.append(thread)
81
-
82
- # Wait for all threads to complete
83
- for t in threads:
84
- t.join()
85
-
86
- # Update session after processing
87
- st.session_state['analyzing'] = False
88
- st.success("πŸŽ‰ Client Details Uploaded Successfully!")
89
- except AttributeError:
90
- st.info("Please fill out all fields first.")
91
- hide_button()
92
 
 
 
 
 
 
 
 
 
 
 
 
93
  def row1(self):
94
- self.client_summary = st.text_area("Client Summary:", help="Name of business, nature of business, location, products/services")
95
- session = st.session_state.analyze
96
- self.name = st.text_input("Client Name:")
97
- self.website = st.text_input("Client Website:")
 
 
 
98
 
99
- if (self.client_summary or self.name or self.website) and session == 'clicked':
100
- self.process() # Call process method to initiate processing
101
 
102
  if __name__ == "__main__":
103
  st.set_page_config(layout="wide")
104
 
105
- upload = uploadFile() # Assuming this is another helper class handling file uploads
 
1
  import streamlit as st
 
2
  from dotenv import load_dotenv
3
  from helper.telemetry import collect_telemetry
4
  from helper.upload_File import uploadFile
5
  from helper.button_behaviour import hide_button
6
+ from helper.initialize_analyze_session import initialize_analyze_session
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  class CientSummary:
10
  def __init__(self):
 
23
  if 'target_market' not in st.session_state:
24
  st.session_state['target_market'] = ''
25
 
26
+ def process (self):
27
+ with st.spinner('Uploading Client Details...', show_time=True):
28
+ st.write('')
29
+ client_summary = ""
30
+ client_name = ""
31
+ client_website = ""
32
+ #
33
+ client_summary = f"Client Summary: {self.client_summary}\n"
34
+ client_name = f"{self.name}\n"
35
+ client_website = f"{self.website}\n"
 
 
 
36
 
37
+ debug_client_summary = {'data_field' : 'Client Summary', 'result': client_summary}
38
+ debug_client_name = {'data_field' : 'Client Name', 'result': client_name}
39
+ debug_client_website = {'data_field' : 'Client Website', 'result': client_website}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ if self.client_summary:
42
+ st.session_state['client_summary'] = 'uploaded'
43
+ st.session_state['target_market'] = 'uploaded'
44
+ collect_telemetry(debug_client_summary)
45
+ if self.name:
46
+ st.session_state['client_name'] = 'uploaded'
47
+ collect_telemetry(debug_client_website)
48
+ if self.website:
49
+ st.session_state['client_website'] = 'uploaded'
50
+ collect_telemetry(debug_client_name)
51
+
52
  def row1(self):
53
+ self.client_summary = st.text_area("Client Summary:", help="Name of business, nature of business, location, products/services")
54
+ session = st.session_state.analyze
55
+ self.name = st.text_input("Client Name:")
56
+ self.website = st.text_input("Client Website:")
57
+
58
+ if (self.client_summary or self.name or self.website) and session == 'clicked':
59
+ self.process()
60
 
 
 
61
 
62
  if __name__ == "__main__":
63
  st.set_page_config(layout="wide")
64
 
65
+ upload = uploadFile()
classes/sem_ppc.py CHANGED
@@ -1,106 +1,161 @@
1
  import streamlit as st
2
- import threading
3
  from dotenv import load_dotenv
4
  from helper.telemetry import collect_telemetry
5
  from helper.upload_File import uploadFile
6
  from helper.button_behaviour import hide_button
7
 
8
- class ThreadSafeHandler:
9
- def __init__(self, placeholder):
10
- self.placeholder = placeholder
11
- self.lock = threading.Lock()
12
-
13
- def update_info(self, message):
14
- with self.lock:
15
- try:
16
- self.placeholder.info(message)
17
- except Exception:
18
- pass
19
-
20
- def update_success(self, message):
21
- with self.lock:
22
- try:
23
- self.placeholder.success(message)
24
- except Exception:
25
- pass
26
-
27
- def update_error(self, message):
28
- with self.lock:
29
- try:
30
- self.placeholder.error(message)
31
- except Exception:
32
- pass
33
 
34
  class Sem_PPC:
35
  def __init__(self, model_url):
36
  self.file_dict = {}
37
  self.model_url = model_url
 
 
 
38
  self.initialize()
39
  self.row1()
40
 
41
  def initialize(self):
 
42
  load_dotenv()
43
- # Initialize session state for various ads
44
- for ad_type in ['account_set_up', 'search_ads', 'display_ads', 'mobile_ads', 'video_ads', 'shopping_ads']:
45
- if ad_type not in st.session_state:
46
- st.session_state[ad_type] = ''
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  def process(self):
49
  session = st.session_state.analyze
50
- if any([self.account_set_up, self.search_ads, self.display_ads, self.mobile_ads, self.video_ads, self.shopping_ads]) and session == 'clicked':
51
- try:
52
- # Prepare ad data
53
- ad_data = {
54
- 'account_set_up': self.account_set_up,
55
- 'search_ads': self.search_ads,
56
- 'display_ads': self.display_ads,
57
- 'mobile_ads': self.mobile_ads,
58
- 'video_ads': self.video_ads,
59
- 'shopping_ads': self.shopping_ads
60
- }
61
-
62
- # Placeholder to display feedback
63
- handler = ThreadSafeHandler(st.empty())
64
-
65
- def upload_ads_data(ad_key, ad_value):
66
  try:
67
- handler.update_info(f"Uploading {ad_key.replace('_', ' ').title()}...")
68
- # Simulate the processing logic here
69
- st.session_state[ad_key] = 'uploaded' # Mock upload success
70
- collect_telemetry({'data_field': ad_key.replace('_', ' ').title(), 'result': ad_value})
71
- handler.update_success(f"{ad_key.replace('_', ' ').title()} completed.")
72
- except Exception as e:
73
- handler.update_error(f"Error uploading {ad_key.replace('_', ' ').title()}: {e}")
74
-
75
- # Start threads for each ad type
76
- threads = []
77
- for ad_key, ad_value in ad_data.items():
78
- thread = threading.Thread(target=upload_ads_data, args=(ad_key, ad_value))
79
- thread.start()
80
- threads.append(thread)
81
-
82
- # Wait for all threads to complete
83
- for t in threads:
84
- t.join()
85
-
86
- # Update session after processing
87
- st.session_state['analyzing'] = False
88
- st.success("πŸŽ‰ SEM/PPC Data Uploaded Successfully!")
89
- except AttributeError:
90
- st.info("Please upload CSV or PDF files first.")
91
- hide_button()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  def row1(self):
94
- self.account_set_up = st.text_input("Account Set Up - Google Ads:", placeholder='Enter Account Set Up')
95
- self.search_ads = st.checkbox("Search Ads - Google Ads/SEMRush")
96
- self.display_ads = st.checkbox("Display Ads - Google Ads/SEMRush")
97
- self.mobile_ads = st.checkbox("Mobile Ads - Google Ads")
98
- self.video_ads = st.checkbox("Video Ads - Google Ads")
99
- self.shopping_ads = st.checkbox("Shopping Ads - Google Ads/SEMRush")
100
-
101
- self.process() # Call process method to initiate processing
102
-
 
 
 
 
 
 
 
 
103
  if __name__ == "__main__":
104
  st.set_page_config(layout="wide")
105
 
106
- upload = uploadFile() # Assuming this is another helper class handling file uploads
 
1
  import streamlit as st
 
2
  from dotenv import load_dotenv
3
  from helper.telemetry import collect_telemetry
4
  from helper.upload_File import uploadFile
5
  from helper.button_behaviour import hide_button
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  class Sem_PPC:
9
  def __init__(self, model_url):
10
  self.file_dict = {}
11
  self.model_url = model_url
12
+ #self.analyst_name = analyst_name
13
+ #self.data_src = data_src
14
+ #self.analyst_description = analyst_description
15
  self.initialize()
16
  self.row1()
17
 
18
  def initialize(self):
19
+ # FOR ENV
20
  load_dotenv()
21
+ '''
22
+ # AGENT NAME
23
+ st.header(self.analyst_name)
24
+
25
+ # EVALUATION FORM LINK
26
+ url = os.getenv('Link')
27
+ st.write('Evaluation Form: [Link](%s)' % url)
28
+
29
+ # RETURN BUTTON
30
+ try:
31
+ if st.button("Return", type='primary'):
32
+ st.switch_page("./pages/home.py")
33
+ except Exception:
34
+ pass
35
+ '''
36
+ if 'account_set_up' not in st.session_state:
37
+ st.session_state['account_set_up'] = ''
38
+ if 'search_ads' not in st.session_state:
39
+ st.session_state['search_ads'] = ''
40
+ if 'display_ads' not in st.session_state:
41
+ st.session_state['display_ads'] = ''
42
+ if 'mobile_ads' not in st.session_state:
43
+ st.session_state['mobile_ads'] = ''
44
+ if 'video_ads' not in st.session_state:
45
+ st.session_state['video_ads'] = ''
46
+ if 'shopping_ads' not in st.session_state:
47
+ st.session_state['shopping_ads'] = ''
48
 
49
  def process(self):
50
  session = st.session_state.analyze
51
+ if (self.account_set_up or self.search_ads or self.display_ads or self.mobile_ads or self.video_ads or self.shopping_ads) and session == 'clicked':
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  try:
53
+ account_set_up = ""
54
+ search_ads = ""
55
+ display_ads = ""
56
+ mobile_ads = ""
57
+ video_ads = ""
58
+ shopping_ads = ""
59
+ with st.spinner('Uploading SEM/PPC...', show_time=True):
60
+ st.write('')
61
+ # INITIALIZING SESSIONS
62
+ #combined_text += f"Client Summary: {st.session_state.nature}\n"
63
+ try:
64
+ account_set_up += f"\nAccount Set Up: {self.account_set_up}"
65
+ except KeyError:
66
+ pass
67
+ try:
68
+ search_ads += f"\nSearch Ads: {self.search_ads}"
69
+ except KeyError:
70
+ pass
71
+ try:
72
+ display_ads += f"\nDisplay Ads: {self.display_ads}"
73
+ except KeyError:
74
+ pass
75
+ try:
76
+ mobile_ads += f"\nMobile Ads: {self.mobile_ads}"
77
+ except KeyError:
78
+ pass
79
+ try:
80
+ video_ads += f"\nVideo Ads: {self.video_ads}"
81
+ except KeyError:
82
+ pass
83
+ try:
84
+ shopping_ads += f"\nShopping Ads: {self.shopping_ads}"
85
+ except KeyError:
86
+ pass
87
+
88
+ # OUTPUT FOR SEO ANALYST
89
+ #payload_txt = {"question": combined_text}
90
+ #result = self.request_model(payload_txt)
91
+
92
+ #end_time = time.time()
93
+ #time_lapsed = end_time - start_time
94
+
95
+ debug_info_account_set_up = {'data_field' : 'Account Set Up - Google Ads', 'result': account_set_up}
96
+ debug_info_search_ads = {'data_field' : 'Search Ads - Google Ads/SEMRush', 'result': search_ads}
97
+ debug_info_display_ads = {'data_field' : 'Display Ads - Google Ads/SEMRush', 'result': display_ads}
98
+ debug_info_mobile_ads = {'data_field' : 'Mobile Ads - Google Ads', 'result': mobile_ads}
99
+ debug_info_video_ads = {'data_field' : 'Video Ads - Google Ads', 'result': video_ads}
100
+ debug_info_shopping_ads = {'data_field' : 'Shopping Ads - Google Ads/SEMRush', 'result': shopping_ads}
101
+
102
+ '''
103
+ debug_info = {
104
+ #'analyst': self.analyst_name,
105
+ 'url_uuid': self.model_url.split("-")[-1],
106
+ 'time_lapsed': time_lapsed,
107
+ 'payload': payload_txt,
108
+ 'result': result,
109
+ }
110
+ '''
111
+ if self.account_set_up:
112
+ st.session_state['account_set_up'] = 'uploaded'
113
+ collect_telemetry(debug_info_account_set_up)
114
+ if self.search_ads:
115
+ st.session_state['search_ads'] = 'uploaded'
116
+ collect_telemetry(debug_info_search_ads)
117
+ if self.display_ads:
118
+ st.session_state['display_ads'] = 'uploaded'
119
+ collect_telemetry(debug_info_display_ads)
120
+ if self.mobile_ads:
121
+ st.session_state['mobile_ads'] = 'uploaded'
122
+ collect_telemetry(debug_info_mobile_ads)
123
+ if self.video_ads:
124
+ st.session_state['video_ads'] = 'uploaded'
125
+ collect_telemetry(debug_info_video_ads)
126
+ if self.shopping_ads:
127
+ st.session_state['shopping_ads'] = 'uploaded'
128
+ collect_telemetry(debug_info_shopping_ads)
129
+
130
+
131
+
132
+ #with st.expander("Debug information", icon="βš™"):
133
+ # st.write(debug_info)
134
+
135
+ st.session_state['analyzing'] = False
136
+ except AttributeError:
137
+ st.info("Please upload CSV or PDF files first.")
138
+ hide_button()
139
 
140
  def row1(self):
141
+ self.account_set_up = st.text_input("Account Set Up - Google Ads:", placeholder='Enter Account Set Up')
142
+ self.search_ads = st.checkbox("Search Ads - Google Ads/SEMRush")
143
+ self.display_ads = st.checkbox("Display Ads - Google Ads/SEMRush")
144
+ self.mobile_ads = st.checkbox("Mobile Ads - Google Ads")
145
+ self.video_ads = st.checkbox("Video Ads - Google Ads")
146
+ self.shopping_ads = st.checkbox("Shopping Ads - Google Ads/SEMRush")
147
+
148
+ '''
149
+ st.write("") # FOR THE HIDE BUTTON
150
+ st.write("") # FOR THE HIDE BUTTON
151
+ st.write("AI Analyst Output: ")
152
+ st.session_state['analyzing'] = False
153
+ st.write("") # FOR THE HIDE BUTTON'
154
+ '''
155
+ #analyze_button = st.button("Analyze", disabled=initialize_analyze_session())
156
+ self.process()
157
+
158
  if __name__ == "__main__":
159
  st.set_page_config(layout="wide")
160
 
161
+ upload = uploadFile()
pages/home.py CHANGED
@@ -45,35 +45,38 @@ class DigitalFootprintDashboard:
45
  st.session_state.analysis_completed = False
46
  if 'uploading' not in st.session_state:
47
  st.session_state['uploading'] = False
 
 
48
 
49
  async def create_row1(self):
50
  """Create the first row with four columns"""
51
  col1, col2, col3, col4, col5 = st.columns(5, border=True, gap="medium", vertical_alignment="top")
52
 
53
  with col1:
54
- button_label = "Uploading..." if st.session_state['uploading'] else "Sync Data"
 
 
 
 
 
 
55
  if st.button(button_label, key="sync_button", icon="πŸ”„", use_container_width=True):
56
  st.session_state['uploading'] = True
57
  st.session_state['analyze'] = 'clicked'
58
 
 
 
 
59
  st.session_state['uploading'] = False
 
60
  else:
61
  st.session_state["analyze"] = ''
62
 
63
- #self.upload_file_button = st.button("Sync Data", st.session_state['analyze'], icon="πŸ”„", use_container_width=True)
64
-
65
- #if self.upload_file_button == True:
66
- # st.session_state["analyze"] = 'clicked'
67
- #unhide_button()
68
- #else:
69
- # st.session_state["analyze"] = ''
70
-
71
  analyze_disabled = st.session_state.get('analyze') != 'clicked'
72
  if st.button("Analyze", key="analyze_button", icon="✨", use_container_width=True, disabled=analyze_disabled):
73
  st.session_state.analysis_completed = False
74
  st.switch_page("pages/analyzing_page.py")
75
 
76
-
77
  self.client_summary = CientSummary()
78
 
79
  with col2:
@@ -106,7 +109,6 @@ class DigitalFootprintDashboard:
106
 
107
  with col5:
108
  st.write("## Website Structure")
109
- #self.crawl = SeoOnCrawl(os.getenv('MODEL_On_Page_Analyst'))
110
  self.on_page = SeoOn(os.getenv('MODEL_On_Page_Analyst'))
111
  self.website_and_tools = WebsiteAndTools(os.getenv('MODEL_On_Page_Analyst'))
112
  self.lld_pm_ln = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))
@@ -117,24 +119,18 @@ class DigitalFootprintDashboard:
117
  async def create_row2(self):
118
  """Create the first row with four columns"""
119
  col1, col4 = st.columns(2, border=True, gap="medium", vertical_alignment="top")
120
- # col1, col2, col3, col4 = st.columns(4, border=True, gap="medium", vertical_alignment="top")
121
 
122
  with col1:
123
  st.write("## Ads")
124
  self.sem_ppc = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))
125
- # with col2:
126
- # st.write("## Amazon")
127
- # self.amazon = Amazon(os.getenv('Model_SEM_PPC_Analyst'))
128
- # with col3:
129
- # st.write("## eBay")
130
- # self.ebay = eBay(os.getenv('Model_SEM_PPC_Analyst'))
131
  with col4:
132
  st.write("## Website Content")
133
  self.content = Content(os.getenv('Model_Content'))
134
  return col1, col4
135
 
136
  async def delete_button(self):
137
- reset_button = st.button("RESET ALL",icon="πŸ—‘οΈ", use_container_width=True)
138
 
139
  if reset_button:
140
  clear_collection("df_data")
@@ -145,9 +141,8 @@ class DigitalFootprintDashboard:
145
  await self.create_row1()
146
  await self.create_row2()
147
  await self.delete_button()
148
- #self.run_analysis()
149
 
150
  # Main execution
151
  if __name__ == "__main__":
152
  dashboard = DigitalFootprintDashboard()
153
- asyncio.run(dashboard.main())
 
45
  st.session_state.analysis_completed = False
46
  if 'uploading' not in st.session_state:
47
  st.session_state['uploading'] = False
48
+ if 'uploaded' not in st.session_state:
49
+ st.session_state['uploaded'] = False # To track if uploading is completed
50
 
51
  async def create_row1(self):
52
  """Create the first row with four columns"""
53
  col1, col2, col3, col4, col5 = st.columns(5, border=True, gap="medium", vertical_alignment="top")
54
 
55
  with col1:
56
+ # Display upload status message
57
+ if st.session_state['uploading']:
58
+ st.info("Uploading...", icon="πŸ”„")
59
+ elif st.session_state['uploaded']:
60
+ st.success("Uploaded successfully!", icon="βœ…")
61
+
62
+ button_label = "Sync Data" if not st.session_state['uploading'] else "Uploading..."
63
  if st.button(button_label, key="sync_button", icon="πŸ”„", use_container_width=True):
64
  st.session_state['uploading'] = True
65
  st.session_state['analyze'] = 'clicked'
66
 
67
+ # Simulating uploading process (can be removed in actual case)
68
+ time.sleep(3) # Simulate upload delay
69
+
70
  st.session_state['uploading'] = False
71
+ st.session_state['uploaded'] = True # Mark as uploaded successfully
72
  else:
73
  st.session_state["analyze"] = ''
74
 
 
 
 
 
 
 
 
 
75
  analyze_disabled = st.session_state.get('analyze') != 'clicked'
76
  if st.button("Analyze", key="analyze_button", icon="✨", use_container_width=True, disabled=analyze_disabled):
77
  st.session_state.analysis_completed = False
78
  st.switch_page("pages/analyzing_page.py")
79
 
 
80
  self.client_summary = CientSummary()
81
 
82
  with col2:
 
109
 
110
  with col5:
111
  st.write("## Website Structure")
 
112
  self.on_page = SeoOn(os.getenv('MODEL_On_Page_Analyst'))
113
  self.website_and_tools = WebsiteAndTools(os.getenv('MODEL_On_Page_Analyst'))
114
  self.lld_pm_ln = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))
 
119
  async def create_row2(self):
120
  """Create the first row with four columns"""
121
  col1, col4 = st.columns(2, border=True, gap="medium", vertical_alignment="top")
 
122
 
123
  with col1:
124
  st.write("## Ads")
125
  self.sem_ppc = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))
126
+
 
 
 
 
 
127
  with col4:
128
  st.write("## Website Content")
129
  self.content = Content(os.getenv('Model_Content'))
130
  return col1, col4
131
 
132
  async def delete_button(self):
133
+ reset_button = st.button("RESET ALL", icon="πŸ—‘οΈ", use_container_width=True)
134
 
135
  if reset_button:
136
  clear_collection("df_data")
 
141
  await self.create_row1()
142
  await self.create_row2()
143
  await self.delete_button()
 
144
 
145
  # Main execution
146
  if __name__ == "__main__":
147
  dashboard = DigitalFootprintDashboard()
148
+ asyncio.run(dashboard.main())