Spaces:
Build error
Build error
snapshot
#8
by notjulietxd - opened
Files changed (44)
- classes/Linkedin.py+1-1
- classes/Off_Page.py+30-72
- classes/On_Page.py+1-3
- classes/On_Page_Crawl.py+1-1
- classes/Seo.py+52-16
- classes/Seo_Backlinks.py+1-1
- classes/Social_Media_FB.py+1-1
- classes/Social_Media_IG.py+1-1
- classes/Tiktok.py+1-1
- classes/Twitter.py+1-1
- classes/Youtube.py+1-1
- classes/amazon.py+15-59
- classes/client_summary.py+7-7
- classes/content.py+9-98
- classes/ebay.py+17-60
- classes/lld_pm_ln.py+1-1
- classes/pull_through_offers.py+1-1
- classes/response_connection_analyst.pyDeleted-87
- classes/response_content.py+1-1
- classes/response_content_process_and_assets_analyst.pyDeleted-100
- classes/response_conversion_analyst.pyDeleted-118
- classes/response_desired_outcome.pyDeleted-88
- classes/response_df_overview.pyDeleted-95
- classes/response_executive_summary.py+3-1
- classes/response_lld_pm_ln.py+1-1
- classes/response_marketplace.py+6-29
- classes/response_off.py+8-6
- classes/response_on_page.py+1-1
- classes/response_pull_through_offers.py+1-1
- classes/response_sem_ppc.py+1-1
- classes/response_seo.py+120-17
- classes/response_snapshot.pyDeleted-101
- classes/response_social_media.py+49-23
- classes/response_target_market.py+1-1
- classes/response_website_and_tools.py+1-1
- classes/response_website_audience_acquisition.pyDeleted-91
- classes/sem_ppc.py+1-1
- classes/website_and_tools.py+1-1
- helper/data_field.py+4-36
- helper/telemetry.py-20
- helper/upload_File.py-42
- pages/analyzing_page.py+117-279
- pages/home.py+36-43
- pages/output.py+66-162
137 unmodified lines138139140141142143144137 unmodified linesif (self.linkedin_f or (self.linkedin_metrics and self.linkedin_metrics.name) or (self.linkedin_post and self.linkedin_post.name)) and session == "clicked":try:combined_text = ""with st.spinner('Uploading Linkedin Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"137 unmodified lines138139140141142143144137 unmodified linesif (self.linkedin_f or (self.linkedin_metrics and self.linkedin_metrics.name) or (self.linkedin_post and self.linkedin_post.name)) and session == "clicked":try:combined_text = ""with st.spinner('Linkedin...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"
2 unmodified lines3456789101112131415 unmodified lines3031323334353637383912 unmodified lines5253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451462 unmodified linesimport streamlit as stimport requestsfrom dotenv import load_dotenvimport timefrom helper.telemetry import collect_telemetryfrom helper.upload_File import uploadFilefrom helper.button_behaviour import hide_button, unhide_buttonfrom helper.initialize_analyze_session import initialize_analyze_sessionimport pandas as pdimport jsonclass SeoOffPageAnalyst:15 unmodified lines#st.header(self.analyst_name)if 'off_page_file_uploaded' not in st.session_state:st.session_state['off_page_file_uploaded'] = ''if 'website_audience' not in st.session_state:st.session_state['website_audience'] = ''if 'uploaded_files' not in st.session_state:st.session_state['uploaded_files'] = ''def request_model(self, payload_txt, headers):response = requests.post(self.model_url, json=payload_txt, headers=headers)12 unmodified linessession = st.session_state['analyze']if self.uploaded_files and session == 'clicked':combined_text = ""website_audience = ""with st.spinner('Uploading Off Page...', show_time=True):st.write('')try:for file_info in st.session_state['uploaded_files'].values():'''if file_info['type'] == 'pdf':combined_text += file_info['content'] + "\n"'''try:if file_info['type'] == 'csv':# Load CSVdf = pd.read_csv(StringIO(file_info['content'].to_csv(index=True)))# Count total rowsnum_rows = len(df)# Extract unique domains from 'Source url'df['Source Domain'] = df['Source url'].apply(lambda x: urlparse(x).netloc)unique_domains = df['Source Domain'].nunique()combined_text += f"Total Backlinks Count: {num_rows}\n"combined_text += f"Referring Domain: {unique_domains}"#st.info("Backlinks - SEMRush Uploaded Successfuly", icon="ℹ️")except KeyError:st.info("Incorrect CSV format. Please upload a valid CSV file.")passexcept UnboundLocalError:passexcept AttributeError:passexcept KeyError:pass'''try:# Check if upload_website_audience exists in session state and is a dictionaryif 'upload_website_audience' in st.session_state and isinstance(st.session_state['upload_website_audience'], dict):for file_name, file_info in st.session_state['upload_website_audience'].items():try:if file_info['type'] == 'csv':# Since file_info['content'] is already a DataFrame (from your earlier code)# No need to convert back from string to DataFramedf = file_info['content']# Process your DataFrame here# Instead of reading from StringIO, just use the DataFrame directlywebsite_audience += f"Website Audience Acquisition {df}\n"#st.info("Website Audience Acquisition Uploaded Successfully", icon="ℹ️")except KeyError:pass#st.info(f"Incorrect format for {file_name}. Please upload a valid CSV file.")except Exception as e:st.error(f"Error processing data: {str(e)}")'''# OUTPUT FOR SEO ANALYST#result = self.request_model(payload_txt, headers)#end_time = time.time()#time_lapsed = end_time - start_timedebug_info = {'data_field' : 'Backlinks', 'result': combined_text}debug_info_website_audience = {'data_field' : 'Website Audience Acquisition', 'result': website_audience}#debug_info = {'url_uuid': self.model_url.split("-")[-1],'time_lapsed' : time_lapsed, 'files': [*st.session_state['uploaded_files']],'payload': payload_txt, 'result': result}if self.uploaded_files:st.session_state['off_page_file_uploaded'] = 'uploaded'collect_telemetry(debug_info)#if self.website_audience:# st.session_state['website_audience'] = 'uploaded'# collect_telemetry(debug_info_website_audience)#with st.expander("Debug information", icon="⚙"):# st.write(debug_info)st.session_state['analyzing'] = Falsedef row1(self):#st.write(self.data_src)self.uploaded_files = st.file_uploader('Backlinks - SEMRush', type='csv', accept_multiple_files=True, key="seo_off")#self.website_audience = st.file_uploader('Website Audience Acquisition - GA4', type='csv', accept_multiple_files=True, key="website_audiences")#self.website_audience = st.text_input("Website Audience Acquisition:", placeholder='Enter Website Audience Acquisition')if self.uploaded_files:upload.multiple_upload_file(self.uploaded_files)#if self.website_audience:# upload.upload_website_audience(self.website_audience)#st.write("") # FOR THE HIDE BUTTON#st.write("") # FOR THE HIDE BUTTON2 unmodified lines34567891011121314151615 unmodified lines32333435363712 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031042 unmodified linesimport streamlit as stimport requestsfrom dotenv import load_dotenvimport osimport timefrom helper.telemetry import collect_telemetryfrom helper.upload_File import uploadFilefrom helper.button_behaviour import hide_button, unhide_buttonfrom helper.initialize_analyze_session import initialize_analyze_sessionimport pandas as pdimport asyncioimport jsonclass SeoOffPageAnalyst:15 unmodified lines#st.header(self.analyst_name)if 'off_page_file_uploaded' not in st.session_state:st.session_state['off_page_file_uploaded'] = ''def request_model(self, payload_txt, headers):response = requests.post(self.model_url, json=payload_txt, headers=headers)12 unmodified linessession = st.session_state['analyze']if self.uploaded_files and session == 'clicked':combined_text = ""with st.spinner('SEO Off Page Analyst...', show_time=True):st.write('')for file_info in st.session_state['uploaded_files'].values():'''if file_info['type'] == 'pdf':combined_text += file_info['content'] + "\n"'''try:if file_info['type'] == 'csv':# Load CSVdf = pd.read_csv(StringIO(file_info['content'].to_csv(index=True)))# Count total rowsnum_rows = len(df)# Extract unique domains from 'Source url'df['Source Domain'] = df['Source url'].apply(lambda x: urlparse(x).netloc)unique_domains = df['Source Domain'].nunique()combined_text += f"Total Backlinks Count: {num_rows}\n"combined_text += f"Referring Domain: {unique_domains}"st.info("Backlinks - SEMRush Uploaded Successfuly", icon="ℹ️")except KeyError:st.info("Incorrect CSV format. Please upload a valid CSV file.")# OUTPUT FOR SEO ANALYSTpayload_txt = {"question": combined_text}headers = {"Content-Type": "application/json","x-api-key": f"{os.getenv('x-api-key')}"}#result = self.request_model(payload_txt, headers)#end_time = time.time()#time_lapsed = end_time - start_timedebug_info = {'data_field' : 'Backlinks', 'result': payload_txt}#debug_info = {'url_uuid': self.model_url.split("-")[-1],'time_lapsed' : time_lapsed, 'files': [*st.session_state['uploaded_files']],'payload': payload_txt, 'result': result}collect_telemetry(debug_info)st.session_state["off_page_file_uploaded"] = 'uploaded'#with st.expander("Debug information", icon="⚙"):# st.write(debug_info)st.session_state['analyzing'] = Falsedef row1(self):#st.write(self.data_src)self.uploaded_files = st.file_uploader('Backlinks - SEMRush', type='csv', accept_multiple_files=True, key="seo_off")if self.uploaded_files:upload.multiple_upload_file(self.uploaded_files)#st.write("") # FOR THE HIDE BUTTON#st.write("") # FOR THE HIDE BUTTON
83 unmodified lines8485868788899028 unmodified lines11912012112212312412512683 unmodified linesif (self.first_meaningful_paint or self.uploaded_files) and session == 'clicked':first_meaningful_paint = ""crawl_file = ""with st.spinner('Uploading On Page...', show_time=True):st.write('')'''try:28 unmodified linespassexcept KeyError:passexcept AttributeError:passtry:first_meaningful_paint += f"\nFirst Meaningful Paint: {self.first_meaningful_paint}"except KeyError:83 unmodified lines8485868788899028 unmodified lines11912012112212312483 unmodified linesif (self.first_meaningful_paint or self.uploaded_files) and session == 'clicked':first_meaningful_paint = ""crawl_file = ""with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')'''try:28 unmodified linespassexcept KeyError:passtry:first_meaningful_paint += f"\nFirst Meaningful Paint: {self.first_meaningful_paint}"except KeyError:
77 unmodified lines7879808182838477 unmodified linessession = st.session_state.analyzeif self.uploaded_files and session == 'clicked':combined_text = ""with st.spinner('Uploading Crawl File...', show_time=True):st.write('')try:for file_info in st.session_state['uploaded_files'].values():77 unmodified lines7879808182838477 unmodified linessession = st.session_state.analyzeif self.uploaded_files and session == 'clicked':combined_text = ""with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')try:for file_info in st.session_state['uploaded_files'].values():
49 unmodified lines50515253545565 unmodified lines1211221231241251261 unmodified line12812913013113213313423 unmodified lines15815916016116216316416516616716816917021 unmodified lines19219319419519619719819920020120220320420520649 unmodified linesst.session_state['df_traffic'] = ''if 'df_seo' not in st.session_state:st.session_state['df_seo'] = ''def detect_encoding(self, uploaded_file):result = chardet.detect(uploaded_file.read(100000))65 unmodified linespassdef process (self):session = st.session_state.analyzeif ((self.uploaded_file or self.others or self.uploaded_file_seo) or (self.page_index or self.bounce_rate)) and session == 'clicked':seo_keywords = ""1 unmodified linetraffic_aqcuisition = ""pages_index = ""bounce_rate = ""with st.spinner('Uploading Seo Files...', show_time=True):st.write('')# INITIALIZING SESSIONS23 unmodified linesexcept AttributeError:passexcept KeyError as e:# Check if 'df_traffic' is the missing key (no file uploaded)if self.uploaded_file_seo:passelse:# This would be triggered if df_traffic exists but the other keys are missingst.info("Incorrect Traffic Channels SEMRush format. Please upload a valid SEMRush file.")try:df_seo = st.session_state['df_seo']21 unmodified linestraffic_aqcuisition += f"Traffics: {traffics}"traffic_aqcuisition += f"\nPaid Traffic: {ga4_paid_social}\nOrganic Traffic: {ga4_organic_traffic}\nDirect Traffic: {ga4_direct_traffic}\nReferral Traffic: {ga4_referral_traffic}"except KeyError:if self.others:passelse:# This would be triggered if df_traffic exists but the other keys are missing#st.info("Incorrect Traffic Acquisition GA4 format. Please upload a valid GA4 file.")passexcept TypeError:st.info("Incorrect Traffic Acquisition GA4 format. Please upload a valid GA4 file.")#result = self.request_model(payload_txt_seo_keywords)#end_time = time.time()49 unmodified lines5051525354555657585960616263646566676869707172737475767778798081828384858687888990919265 unmodified lines1581591601611621631641651 unmodified line16716816917017117217323 unmodified lines19719819920020120220320421 unmodified lines22622722822923023123223323423523623723823924024124249 unmodified linesst.session_state['df_traffic'] = ''if 'df_seo' not in st.session_state:st.session_state['df_seo'] = ''def request_model(self, payload_txt):response = requests.post(self.model_url, json=payload_txt)response.raise_for_status()output = response.json()categories = []current_footprint = []number_of_backlinks = []for key, value in output.items():if key == 'json':for item in value:categories.append(item.get('category', 'N/A').replace('_', ' ').title())current_footprint.append(item.get('current_footprint', 'N/A'))number_of_backlinks.append(item.get('best_of_breed_solution', 'N/A'))output = ""for i in range(len(categories)):output += f"\n\n---\n **Category:** {categories[i]}"output += f"\n\n **Current Footprint:** {current_footprint[i]}\n\n"output += f"**Number of Backlinks:** {number_of_backlinks[i]}"data = {"": [str(category) for category in categories],"Current Footprint": [str(footprint) for footprint in current_footprint],"Best of Breed Solutions": [str(backlink) for backlink in number_of_backlinks]}df_output = pd.DataFrame(data)with st.expander("AI Analysis", expanded=True, icon="🤖"):st.table(df_output.style.set_table_styles([{'selector': 'th:first-child, td:first-child', 'props': [('width', '20px')]},{'selector': 'th, td', 'props': [('width', '150px'), ('text-align', 'center')]}]).set_properties(**{'text-align': 'center'}))return outputdef detect_encoding(self, uploaded_file):result = chardet.detect(uploaded_file.read(100000))65 unmodified linespassdef process (self):start_time = time.time()session = st.session_state.analyzeif ((self.uploaded_file or self.others or self.uploaded_file_seo) or (self.page_index or self.bounce_rate)) and session == 'clicked':seo_keywords = ""1 unmodified linetraffic_aqcuisition = ""pages_index = ""bounce_rate = ""with st.spinner('Seo Analyst...', show_time=True):st.write('')# INITIALIZING SESSIONS23 unmodified linesexcept AttributeError:passexcept KeyError:st.info("Incorrect SEMRush format. Please upload a valid SEMRush file.")try:df_seo = st.session_state['df_seo']21 unmodified linestraffic_aqcuisition += f"Traffics: {traffics}"traffic_aqcuisition += f"\nPaid Traffic: {ga4_paid_social}\nOrganic Traffic: {ga4_organic_traffic}\nDirect Traffic: {ga4_direct_traffic}\nReferral Traffic: {ga4_referral_traffic}"except KeyError:passexcept TypeError:st.info("Incorrect GA4 format. Please upload a valid GA4 file.")# OUTPUT FOR SEO ANALYSTpayload_txt_seo_keywords = {"question": seo_keywords}payload_txt_traffic_channels = {"question": traffic_channels}payload_txt_traffic_aqcuisition = {"question": traffic_aqcuisition}payload_txt_pages_index = {"question": pages_index}payload_txt_bounce_rate = {"question": bounce_rate}#result = self.request_model(payload_txt_seo_keywords)#end_time = time.time()
213 unmodified lines214215216217218219220213 unmodified lineshide_button()if self.uploaded_files:combined_text = ""with st.spinner('Uploading Backlinks...', show_time=True):st.write('')'''# INITIALIZING SESSIONS213 unmodified lines214215216217218219220213 unmodified lineshide_button()if self.uploaded_files:combined_text = ""with st.spinner('Analyzing...', show_time=True):st.write('')'''# INITIALIZING SESSIONS
146 unmodified lines147148149150151152153146 unmodified linesif ((self.fb_organic_post and self.fb_organic_post.name) or (self.fb_ads_campaign and self.fb_ads_campaign.name) or (self.facebooks) or (self.facebook_rr)) and session == 'clicked':try:combined_text = ""with st.spinner('Uploading FB Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"146 unmodified lines147148149150151152153146 unmodified linesif ((self.fb_organic_post and self.fb_organic_post.name) or (self.fb_ads_campaign and self.fb_ads_campaign.name) or (self.facebooks) or (self.facebook_rr)) and session == 'clicked':try:combined_text = ""with st.spinner('Social Media Analyst...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"
109 unmodified lines110111112113114115116109 unmodified linesif (self.instagram or self.instagram_er or self.instagram_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Uploading IG Files...', show_time=True):st.write('')try:combined_text += f"\nInstagram Followers: {self.instagram}"109 unmodified lines110111112113114115116109 unmodified linesif (self.instagram or self.instagram_er or self.instagram_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Instagram...', show_time=True):st.write('')try:combined_text += f"\nInstagram Followers: {self.instagram}"
108 unmodified lines109110111112113114115108 unmodified linesif (self.tiktok_f or self.tiktok_er or self.tiktok_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Uploading Tiktok Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"108 unmodified lines109110111112113114115108 unmodified linesif (self.tiktok_f or self.tiktok_er or self.tiktok_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Tiktok...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"
120 unmodified lines121122123124125126127120 unmodified linesif (self.twitter or self.twitter_er or self.twitter_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Uploading Twitter Files...', show_time=True):st.write('')# INITIALIZING SESSIONScombined_text += f"Client Summary: {st.session_state.nature}\n"120 unmodified lines121122123124125126127120 unmodified linesif (self.twitter or self.twitter_er or self.twitter_pf) and session == 'clicked':try:combined_text = ""with st.spinner('Twitter...', show_time=True):st.write('')# INITIALIZING SESSIONScombined_text += f"Client Summary: {st.session_state.nature}\n"
108 unmodified lines109110111112113114115108 unmodified linesif ((self.youtube or self.youtube_er or self.youtube_pf) and session) == 'clicked':try:combined_text = ""with st.spinner('Uploading YT Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"108 unmodified lines109110111112113114115108 unmodified linesif ((self.youtube or self.youtube_er or self.youtube_pf) and session) == 'clicked':try:combined_text = ""with st.spinner('Youtube...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"
30 unmodified lines313233343536372 unmodified lines4041424344454647484950515253545556575859606162636410 unmodified lines75767778798081828384851 unmodified line878889909192939495969798993 unmodified lines1031041051061071086 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516630 unmodified linesst.switch_page("./pages/home.py")except Exception:passif 'product_title_amazon' not in st.session_state:st.session_state['product_title_amazon'] = ''if 'images_amazon' not in st.session_state:2 unmodified linesst.session_state['bullet_points_amazon'] = ''if 'product_description_amazon' not in st.session_state:st.session_state['product_description_amazon'] = '''''if 'amazon_marketplace_questionnaires' not in st.session_state:st.session_state['amazon_marketplace_questionnaires'] = ''def process(self):session = st.session_state.analyzeif (self.amazon_marketplace_questionnaires) and session == 'clicked':try:#product_title_amazon = ""#images_amazon = ""#bullet_points_amazon = ""#product_description_amazon = ""amazon_marketplace_questionnaires = ""with st.spinner('Uploading Amazon Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"'''try:product_title_amazon += f"\nProduct Title: {self.product_title_amazon}"except KeyError:10 unmodified linesproduct_description_amazon += f"\nProduct Description: {self.product_description_amazon}"except KeyError:pass'''try:amazon_marketplace_questionnaires += f"Marketplace Questionnaires - Amazon: {self.amazon_marketplace_questionnaires}"except KeyError:pass# OUTPUT FOR SEO ANALYST#payload_txt = {"question": combined_text}1 unmodified line#end_time = time.time()#time_lapsed = end_time - start_time'''debug_info_product_title_amazon = {'data_field' : 'Product Title - Amazon', 'result': self.product_title_amazon}debug_info_images_amazon = {'data_field' : 'Images - Amazon', 'result': self.images_amazon}debug_info_bullet_points_amazon = {'data_field' : 'Bullet Points - Amazon', 'result': self.bullet_points_amazon}debug_product_description_amazon = {'data_field' : 'Product Description - Amazon', 'result': self.product_description_amazon}'''debug_amazon_marketplace_questionnaires = {'data_field' : 'Marketplace Questionnaires - Amazon', 'result': self.amazon_marketplace_questionnaires}'''debug_info = {3 unmodified lines'payload': payload_txt,'result': result,}if self.product_title_amazon:st.session_state['product_title_amazon'] = 'uploaded'collect_telemetry(debug_info_product_title_amazon)6 unmodified linesif self.product_description_amazon:st.session_state['product_description_amazon'] = 'uploaded'collect_telemetry(debug_product_description_amazon)'''if self.amazon_marketplace_questionnaires:if self.amazon_marketplace_questionnaires != self.template:st.session_state['amazon_marketplace_questionnaires'] = 'uploaded'collect_telemetry(debug_amazon_marketplace_questionnaires)else:passst.session_state['analyzing'] = Falseexcept AttributeError:st.info("Please upload CSV or PDF files first.")hide_button()def row1(self):#self.product_title_amazon = st.text_input("Product Title - Amazon:", placeholder='Enter Product Title')#self.images_amazon = st.text_input("Images - Amazon:", placeholder='Enter Images')#self.bullet_points_amazon = st.text_input("Bullet Points - Amazon:", placeholder='Enter Bullet Points')#self.product_description_amazon = st.text_input("Product Description - Amazon:", placeholder='Enter Product Description')self.template = ("Product Title:\n""a. Does the product title include relevant keywords (e.g., Product Brand/Description + Product Line + Material or Key Ingredient + Color + Size + Quantity)?\n""b. Is the title within Amazon’s recommended character limit (≤200 characters)?\n""c. Other Remarks:\n\n""Images:\n""a. Is the main image on a pure white background?\n""b. Are there any logos, watermarks, or text on any images?\n""c. Do the images showcase the product from multiple angles?\n""d. Are the images high-resolution and zoomable?\n""e. Other Remarks:\n\n""Bullet Points:\n""a. Do the bullets exceed 250 characters?\n""b. Are the bullet points clear and concise?\n""c. Do they highlight key features, benefits, and unique selling points?\n""d. Are keywords naturally included in the bullet points?\n""e. Other Remarks:\n\n""Product Description:\n""a. Is the product description complete and well-formatted?\n""b. Is it within the 2000-character limit?\n""c. Does it include important product specifications (size, material, compatibility)?\n""d. Are there any customer reviews or ratings?\n""e. If yes, is the average rating above 4 stars?\n""f. Other Remarks:")self.amazon_marketplace_questionnaires = st.text_area("Marketplace Questionnaires - Amazon:",value=self.template,height=600)self.process()if __name__ == "__main__":30 unmodified lines313233343536372 unmodified lines404142434445464748495051525354555657585910 unmodified lines7071727374751 unmodified line77787980818283848586873 unmodified lines919293949596976 unmodified lines10410510610710810911011111211311411511611711811912012112230 unmodified linesst.switch_page("./pages/home.py")except Exception:pass'''if 'product_title_amazon' not in st.session_state:st.session_state['product_title_amazon'] = ''if 'images_amazon' not in st.session_state:2 unmodified linesst.session_state['bullet_points_amazon'] = ''if 'product_description_amazon' not in st.session_state:st.session_state['product_description_amazon'] = ''def process(self):session = st.session_state.analyzeif (self.product_title_amazon or self.images_amazon or self.bullet_points_amazon or self.product_description_amazon) and session == 'clicked':try:product_title_amazon = ""images_amazon = ""bullet_points_amazon = ""product_description_amazon = ""with st.spinner('Aamzon...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"try:product_title_amazon += f"\nProduct Title: {self.product_title_amazon}"except KeyError:10 unmodified linesproduct_description_amazon += f"\nProduct Description: {self.product_description_amazon}"except KeyError:pass# OUTPUT FOR SEO ANALYST#payload_txt = {"question": combined_text}1 unmodified line#end_time = time.time()#time_lapsed = end_time - start_timedebug_info_product_title_amazon = {'data_field' : 'Product Title - Amazon', 'result': self.product_title_amazon}debug_info_images_amazon = {'data_field' : 'Images - Amazon', 'result': self.images_amazon}debug_info_bullet_points_amazon = {'data_field' : 'Bullet Points - Amazon', 'result': self.bullet_points_amazon}debug_product_description_amazon = {'data_field' : 'Product Description - Amazon', 'result': self.product_description_amazon}'''debug_info = {3 unmodified lines'payload': payload_txt,'result': result,}'''if self.product_title_amazon:st.session_state['product_title_amazon'] = 'uploaded'collect_telemetry(debug_info_product_title_amazon)6 unmodified linesif self.product_description_amazon:st.session_state['product_description_amazon'] = 'uploaded'collect_telemetry(debug_product_description_amazon)st.session_state['analyzing'] = Falseexcept AttributeError:st.info("Please upload CSV or PDF files first.")hide_button()def row1(self):self.product_title_amazon = st.text_input("Product Title - Amazon:", placeholder='Enter Product Title')self.images_amazon = st.text_input("Images - Amazon:", placeholder='Enter Images')self.bullet_points_amazon = st.text_input("Bullet Points - Amazon:", placeholder='Enter Bullet Points')self.product_description_amazon = st.text_input("Product Description - Amazon:", placeholder='Enter Product Description')self.process()if __name__ == "__main__":
5 unmodified lines67891011125 unmodified lines1819202122232425262728293013 unmodified lines444546474849505152535 unmodified linesfrom helper.initialize_analyze_session import initialize_analyze_sessionclass ClientSummary:def __init__(self):self.initialize()self.row1()5 unmodified linesst.session_state['client_summary'] = ''if 'client_name' not in st.session_state:st.session_state['client_name'] = ''if 'client_website' not in st.session_state:st.session_state['client_website'] = ''if 'target_market' not in st.session_state:st.session_state['target_market'] = ''def process (self):with st.spinner('Uploading Client Details...', show_time=True):st.write('')client_summary = ""client_name = ""13 unmodified linescollect_telemetry(debug_client_summary)if self.name:st.session_state['client_name'] = 'uploaded'collect_telemetry(debug_client_name)if self.website:st.session_state['client_website'] = 'uploaded'collect_telemetry(debug_client_website)def row1(self):self.client_summary = st.text_area("Client Summary:", help="Name of business, nature of business, location, products/services")5 unmodified lines67891011125 unmodified lines1819202122232425262728293013 unmodified lines444546474849505152535 unmodified linesfrom helper.initialize_analyze_session import initialize_analyze_sessionclass CientSummary:def __init__(self):self.initialize()self.row1()5 unmodified linesst.session_state['client_summary'] = ''if 'client_name' not in st.session_state:st.session_state['client_name'] = ''if 'client_webiste' not in st.session_state:st.session_state['client_webiste'] = ''if 'target_market' not in st.session_state:st.session_state['target_market'] = ''def process (self):with st.spinner('Seo Analyst...', show_time=True):st.write('')client_summary = ""client_name = ""13 unmodified linescollect_telemetry(debug_client_summary)if self.name:st.session_state['client_name'] = 'uploaded'collect_telemetry(debug_client_website)if self.website:st.session_state['client_webiste'] = 'uploaded'collect_telemetry(debug_client_name)def row1(self):self.client_summary = st.text_area("Client Summary:", help="Name of business, nature of business, location, products/services")
34 unmodified lines3536373839404110 unmodified lines5253545556575859606162636465666768695 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516634 unmodified linessession = st.session_state.analyzeif (self.content_in_the_website or self.content_outside_the_website) and session == 'clicked':with st.spinner('Uploading Contents...', show_time=True):st.write('')content_in_the_website = ""content_outside_the_website = ""10 unmodified linesdebug_info_content_outside_the_website = {'data_field' : 'Content outside the Website', 'result': content_outside_the_website}if self.content_in_the_website:if self.content_in_the_website != self.template_content_in_the_website:st.session_state['content_in_the_website'] = 'uploaded'collect_telemetry(debug_info_content_in_the_website)else:passif self.content_outside_the_website:if self.content_outside_the_website != self.template_content_outside_the_website:st.session_state['content_outside_the_website'] = 'uploaded'collect_telemetry(debug_info_content_outside_the_website)else:pass#with st.expander("Debug information", icon="⚙"):# st.write(debug_info)5 unmodified linespassdef row1(self):self.template_content_in_the_website = ("Content and Messaging:\n""a. Is the text easy to read and understand?\n""b. Does it clearly explain what the business offers?\n""c. Are the brand’s Unique Selling Propositions (USPs) clearly emphasized?\n""d. Other Remarks:\n\n""Call-to-Action (CTAs):\n""a. Are CTAs prominently placed and easy to find?\n""b. Are the CTAs strong and action-focused?\n""c. Do they appear in the right places?\n""d. Other Remarks:\n\n""Images and Videos:\n""a. Are the images and videos high quality?\n""b. Do they clearly show the product or service?\n""c. Are the videos easy to watch (no unnecessary clicks or extra steps)?\n""d. Are the visuals engaging upon first glance?\n""e. Other Remarks:\n\n""Blog and SEO:\n""a. Does the site have a blog section?\n""b. Is the blog updated regularly?\n""c. Are the articles helpful, relevant, and informative?\n""d. Are internal links used to guide users to related or deeper content?\n""e. Other Remarks:\n\n""User Experience (UX) and Navigation:\n""a. Is the site easy to navigate with clear menus and categories?\n""b. Can users quickly find important information?\n""c. Are any interactions creating unnecessary friction (e.g., signups to view content)?\n""d. Other Remarks:\n\n""Product or Services (For E-Commerce):\n""a. Does the site clearly explain the company’s products or services?\n""b. Are product or service details clear?\n""c. Are there enough pictures or videos?\n""d. Is there a sense of urgency or promotions to encourage action?\n""e. Other Remarks:")self.template_content_outside_the_website = ("Backlinks and Referring Domains:\n""a. Are there backlinks from relevant and authoritative websites?\n""b. Do the referring sites belong to the same industry or niche?\n""c. Are there spammy or low-quality backlinks (e.g., thin directories)?\n""d. Are the backlinks helpful and align with Google’s Helpful Content guidelines?\n""e. Are there any guest posts or articles on other websites?\n""f. Other Remarks:\n\n""Community Engagement (Forums and Platforms):\n""a. Is the brand/product/company mentioned in online forums (e.g., Reddit, or Quora)?\n""b. Are the mentions from forums and platforms generally positive?\n""c. Are the mentions from forums and platforms generally negative?\n""d. Is it actively participating or present in these communities?\n""e. Is there a strategy for using personas or ambassadors to represent the client’s company/brand/product?\n""f. Other Remarks:\n\n""Online Reviews and Reputation Management:\n""a. Are there recent reviews on platforms like Google, Trustpilot, or Yelp?\n""b. Are the reviews mostly positive?\n""c. Are the reviews mostly negative?\n""d. Is the client responding to reviews, especially complaints or fake ones?\n""e. Do the reviews mention recurring issues (e.g., poor support, unsolicited emails)?\n""f. Other Remarks:\n\n""Public Relations and Media Coverage:\n""a. Has the client’s company been featured in news sites or magazines?\n""b. Are the articles helpful and recent?\n""c. Are PR opportunities being used to boost awareness?\n""d. Other Remarks:\n\n""Branded Blog Networks:\n""a. Are there any off-page blog sites created by the client’s company?\n""b. Is the content unique, helpful, and adding SEO value?\n""c. Can the content be moved or consolidated into the main site?\n""d. Other Remarks:\n\n""Email Marketing & CRM Engagement:\n""a. Is email being used to follow up with customers or leads (e.g., newsletters, cart recovery)?\n""b. Are they sending follow-up emails?\n""c. Are emails building relationships and promoting content or reviews?\n""d. Other Remarks:")self.content_in_the_website = st.text_area("Content in the Website:",value=self.template_content_in_the_website,height=600)self.content_outside_the_website = st.text_area("Content outside the Website:",value=self.template_content_outside_the_website,height=600)self.process()34 unmodified lines3536373839404110 unmodified lines525354555657585960616263645 unmodified lines707172737475767734 unmodified linessession = st.session_state.analyzeif (self.content_in_the_website or self.content_outside_the_website) and session == 'clicked':with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')content_in_the_website = ""content_outside_the_website = ""10 unmodified linesdebug_info_content_outside_the_website = {'data_field' : 'Content outside the Website', 'result': content_outside_the_website}if self.content_in_the_website:st.session_state['content_in_the_website'] = 'uploaded'collect_telemetry(debug_info_content_in_the_website)if self.content_outside_the_website:st.session_state['content_outside_the_website'] = 'uploaded'collect_telemetry(debug_info_content_outside_the_website)#with st.expander("Debug information", icon="⚙"):# st.write(debug_info)5 unmodified linespassdef row1(self):self.content_in_the_website = st.text_input("Content in the Website (Website Content)", placeholder='Enter Content in the Website')self.content_outside_the_website = st.text_input("Content outside the Website (Website Content)", placeholder='Enter Content outside the Website')self.process()
30 unmodified lines313233343536372 unmodified lines4041424344454647484950515253545556575859606162636410 unmodified lines75767778798081828384852 unmodified lines8889909192939495969798993 unmodified lines1031041051061071081096 unmodified lines1161171181191201211221231241251261271281 unmodified line13013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416530 unmodified linesst.switch_page("./pages/home.py")except Exception:passif 'product_title_ebay' not in st.session_state:st.session_state['product_title_ebay'] = ''if 'category_ebay' not in st.session_state:2 unmodified linesst.session_state['images_ebay'] = ''if 'product_description_ebay' not in st.session_state:st.session_state['product_description_ebay'] = '''''if 'ebay_marketplace_questionnaires' not in st.session_state:st.session_state['ebay_marketplace_questionnaires'] = ''def process(self):session = st.session_state.analyzeif (self.ebay_marketplace_questionnaires) and session == 'clicked':try:#product_title_ebay = ""#category_ebay = ""#images_ebay = ""#product_description_ebay = ""ebay_marketplace_questionnaires = ""with st.spinner('Uploading Ebay Files...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"'''try:product_title_ebay += f"\nProduct Title: {self.product_title_ebay}"except KeyError:10 unmodified linesproduct_description_ebay += f"\nProduct Description: {self.product_description_ebay}"except KeyError:pass'''try:ebay_marketplace_questionnaires += f"Marketplace Questionnaires - eBay: {self.ebay_marketplace_questionnaires}"except KeyError:pass# OUTPUT FOR SEO ANALYST#payload_txt = {"question": combined_text}2 unmodified lines#end_time = time.time()#time_lapsed = end_time - start_time#debug_info_product_title_ebay = {'data_field' : 'Product Title - eBay', 'result': self.product_title_ebay}#debug_category_ebay = {'data_field' : 'Category - eBay', 'result': self.category_ebay}#debug_images_ebay = {'data_field' : 'Images - eBay', 'result': self.images_ebay}#debug_product_description_ebay = {'data_field' : 'Product Description - eBay', 'result': self.product_description_ebay}debug_ebay_marketplace_questionnaires = {'data_field' : 'Marketplace Questionnaires - eBay', 'result': self.ebay_marketplace_questionnaires}'''debug_info = {3 unmodified lines'payload': payload_txt,'result': result,}if self.product_title_ebay:st.session_state['product_title_ebay'] = 'uploaded'collect_telemetry(debug_info_product_title_ebay)6 unmodified linesif self.product_description_ebay:st.session_state['product_description_ebay'] = 'uploaded'collect_telemetry(debug_product_description_ebay)'''if self.ebay_marketplace_questionnaires:if self.ebay_marketplace_questionnaires != self.template:st.session_state['ebay_marketplace_questionnaires'] = 'uploaded'collect_telemetry(debug_ebay_marketplace_questionnaires)else:passst.session_state['analyzing'] = Falseexcept AttributeError:1 unmodified linehide_button()def row1(self):#self.product_title_ebay = st.text_input("Product Title - eBay:", placeholder='Enter Product Title')#self.category_ebay = st.text_input("Images - eBay:", placeholder='Enter Images')#self.images_ebay = st.text_input("Bullet Points - eBay:", placeholder='Enter Bullet Points')#self.product_description_ebay = st.text_input("Product Description - eBay:", placeholder='Enter Product Description')self.template = ("Product Title:\n""a. Is the title within the 80-character limit?\n""b. Does the title include important details (e.g., brand, color, quantity, compatibility)?\n""c. Are search keywords used effectively in the title?\n""d. Other Remarks:\n\n""Category:\n""a. Is the product listed under the correct eBay category?\n""b. Other Remarks:\n\n""Images:\n""a. Are the product images on a white background?\n""b. Are there any text, logos, or watermarks on the images?\n""c. Are the images high-resolution and zoomable?\n""d. Other Remarks:\n\n""Product Description:\n""a. Is the product description complete and detailed?\n""b. Are bullet points used to highlight features and benefits?\n""c. Are there images embedded in the description?\n""d. Are there any technical issues (e.g., broken images, loading errors)?\n""e. Is there consistent keyword usage in the description?\n""f. Other Remarks:")self.ebay_marketplace_questionnaires = st.text_area("Marketplace Questionnaires - eBay:",value=self.template,height=600)self.process()if __name__ == "__main__":30 unmodified lines313233343536372 unmodified lines404142434445464748495051525354555657585910 unmodified lines7071727374752 unmodified lines787980818283848586873 unmodified lines919293949596976 unmodified lines1041051061071081091101 unmodified line11211311411511611711811912012112230 unmodified linesst.switch_page("./pages/home.py")except Exception:pass'''if 'product_title_ebay' not in st.session_state:st.session_state['product_title_ebay'] = ''if 'category_ebay' not in st.session_state:2 unmodified linesst.session_state['images_ebay'] = ''if 'product_description_ebay' not in st.session_state:st.session_state['product_description_ebay'] = ''def process(self):session = st.session_state.analyzeif (self.product_title_ebay or self.category_ebay or self.images_ebay or self.product_description_ebay) and session == 'clicked':try:product_title_ebay = ""category_ebay = ""images_ebay = ""product_description_ebay = ""with st.spinner('eBay...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"try:product_title_ebay += f"\nProduct Title: {self.product_title_ebay}"except KeyError:10 unmodified linesproduct_description_ebay += f"\nProduct Description: {self.product_description_ebay}"except KeyError:pass# OUTPUT FOR SEO ANALYST#payload_txt = {"question": combined_text}2 unmodified lines#end_time = time.time()#time_lapsed = end_time - start_timedebug_info_product_title_ebay = {'data_field' : 'Product Title - eBay', 'result': self.product_title_ebay}debug_category_ebay = {'data_field' : 'Category - eBay', 'result': self.category_ebay}debug_images_ebay = {'data_field' : 'Images - eBay', 'result': self.images_ebay}debug_product_description_ebay = {'data_field' : 'Product Description - eBay', 'result': self.product_description_ebay}'''debug_info = {3 unmodified lines'payload': payload_txt,'result': result,}'''if self.product_title_ebay:st.session_state['product_title_ebay'] = 'uploaded'collect_telemetry(debug_info_product_title_ebay)6 unmodified linesif self.product_description_ebay:st.session_state['product_description_ebay'] = 'uploaded'collect_telemetry(debug_product_description_ebay)st.session_state['analyzing'] = Falseexcept AttributeError:1 unmodified linehide_button()def row1(self):self.product_title_ebay = st.text_input("Product Title - eBay:", placeholder='Enter Product Title')self.category_ebay = st.text_input("Images - eBay:", placeholder='Enter Images')self.images_ebay = st.text_input("Bullet Points - eBay:", placeholder='Enter Bullet Points')self.product_description_ebay = st.text_input("Product Description - eBay:", placeholder='Enter Product Description')self.process()if __name__ == "__main__":
33 unmodified lines3435363738394033 unmodified linessession = st.session_state.analyzeif (self.lead_generation_mechanism) and session == 'clicked':lead_generation_mechanism = ""with st.spinner('Uploading Lead Generation...', show_time=True):st.write('')try:33 unmodified lines3435363738394033 unmodified linessession = st.session_state.analyzeif (self.lead_generation_mechanism) and session == 'clicked':lead_generation_mechanism = ""with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')try:
29 unmodified lines3031323334353629 unmodified linessession = st.session_state.analyzeif (self.pull_through_offers) and session == 'clicked':pull_through_offers = ""with st.spinner('Uploading Pull Through Offers...', show_time=True):st.write('')try:29 unmodified lines3031323334353629 unmodified linessession = st.session_state.analyzeif (self.pull_through_offers) and session == 'clicked':pull_through_offers = ""with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')try:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientimport json
class ConnectionAnalyst: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] #text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Connection Analyst...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Connection Analyst', 'result': payload_txt_model} upload_response(debug_info)
count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_client_summary = st.session_state['client_summary'] if session_client_summary == 'uploaded': count += 1 self.payload += self.fetch_data("Client Summary") except Exception as e: pass if count >= 1: self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Content Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Content Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientimport jsonclass Content_Process_and_Assets_Analyst: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Content - Process and Assets Analyst...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Content - Process and Assets Analyst', 'result': payload_txt_model} upload_response(debug_info)
count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_client_summary = st.session_state['client_summary'] if session_client_summary == 'uploaded': count += 1 self.payload += self.fetch_data("Client Summary") except Exception as e: pass try: session_content_in_the_website = st.session_state['content_in_the_website'] if session_content_in_the_website == 'uploaded': count += 1 self.payload += self.fetch_data("Content in the Website") except Exception as e: pass try: session_content_outside_the_website = st.session_state['content_outside_the_website'] if session_content_outside_the_website == 'uploaded': count += 1 self.payload += self.fetch_data("Content outside the Website") except Exception as e: pass if count >= 3: self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientimport json
class ConversionAnalyst: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Conversion Analyst...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Conversion Analyst', 'result': payload_txt_model} upload_response(debug_info)
count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_lead_generation_mechanism = st.session_state['lead_generation_mechanism'] if session_lead_generation_mechanism == 'uploaded': count += 1 self.payload += self.fetch_data("Lead Generation Mechanism") except Exception as e: pass try: session_client_relations_management_system = st.session_state['client_relations_management_system'] if session_client_relations_management_system == 'uploaded': count += 1 self.payload += self.fetch_data("Client Relations Management System") except Exception as e: pass try: session_pull_through_offers = st.session_state['pull_through_offers'] if session_pull_through_offers == 'uploaded': count += 1 self.payload += self.fetch_data("Pull through offers") except Exception as e: pass try: session_content_in_the_website = st.session_state['content_in_the_website'] if session_content_in_the_website == 'uploaded': count += 1 self.payload += self.fetch_data("Content in the Website") except Exception as e: pass try: session_content_outside_the_website = st.session_state['content_outside_the_website'] if session_content_outside_the_website == 'uploaded': count += 1 self.payload += self.fetch_data("Content outside the Website") except Exception as e: pass if count >= 1: name = self.fetch_data("Client Name") website = self.fetch_data("Client Website") self.payload = name + website + self.payload self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientimport json
class DesiredOutcome: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] #text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Desired Outcome Analyst...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Desired Outcomes Analyst', 'result': payload_txt_model} upload_response(debug_info)
st.session_state['client_summary'] = '' count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_client_summary = st.session_state['client_summary'] if session_client_summary == 'uploaded': count += 1 self.payload += self.fetch_data("Client Summary") except Exception as e: pass if count >= 1: self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495from io import StringIOfrom urllib.parse import urlparseimport streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFileimport jsonfrom pymongo import MongoClient
class dfOverview: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] #text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('DF Overview Analyst...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'DF Overview Analyst', 'result': payload_txt_model} upload_response(debug_info)
st.session_state['client_summary'] = '' st.session_state['client_name'] = '' count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_client_summary = st.session_state['client_summary'] if session_client_summary == 'uploaded': count += 1 self.payload += self.fetch_data("Client Summary") self.payload += self.fetch_data("Client Name") except Exception as e: pass if count >= 1: summary = self.fetch_data("Client Summary") self.payload = summary + self.payload self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()12345678944 unmodified lines54555657585960import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientfrom helper.data_field import get_analyst_response44 unmodified linesdef process(self):with st.spinner('Executive Summary...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)123456789101144 unmodified lines56575859606162from urllib.parse import urlparseimport streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFileimport jsonfrom pymongo import MongoClientfrom helper.data_field import get_analyst_response44 unmodified linesdef process(self):with st.spinner('Executive Summary...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
72 unmodified lines7374757677787972 unmodified linesdef process(self):with st.spinner('LLD/PM/LN Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)72 unmodified lines7374757677787972 unmodified linesdef process(self):with st.spinner('LLD/PM/LN Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
38 unmodified lines3940414243444546474849505122 unmodified lines747576777879808182838485862 unmodified lines8990919293949596975 unmodified lines10310410510610710810952 unmodified lines16216316416516616716816917017117217317417517617717817918018118218338 unmodified linesresponse.raise_for_status()output = response.json()#st.write(output)text_amazon = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"]#text_ebay = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"]["ebay"]text_amazon = json.loads(text_amazon)#text_ebay = json.loads(text_ebay)#text = text_amazon + text_ebay#st.write(text_amazon)return text_amazondef fetch_backlinks(self, data_field):mongodb_uri = os.getenv("MONGODB_URI")22 unmodified linesdef process (self):with st.spinner('Marketplace Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)debug_info = {'data_field' : 'Marketplace Analyst', 'result': payload_txt_model}upload_response(debug_info)'''st.session_state['product_title_amazon'] = ''st.session_state['images_amazon'] = ''st.session_state['bullet_points_amazon'] = ''2 unmodified linesst.session_state['category_ebay'] = ''st.session_state['images_ebay'] = ''st.session_state['product_description_ebay'] = '''''st.session_state['amazon_marketplace_questionnaires'] = ''st.session_state['ebay_marketplace_questionnaires'] = ''count = 0except Exception as e:pass5 unmodified lines#analyze_button = st.button("Analyze", disabled=initialize_analyze_session())self.payload = ""count = 0'''try:session_product_title_amazon = st.session_state['product_title_amazon']if session_product_title_amazon == 'uploaded':52 unmodified linesself.payload += self.fetch_data("Product Description - eBay")except Exception as e:pass'''try:session_amazon_marketplace_questionnaires = st.session_state['amazon_marketplace_questionnaires']if session_amazon_marketplace_questionnaires == 'uploaded':count += 1self.payload += self.fetch_data("Marketplace Questionnaires - Amazon")except Exception as e:passtry:session_ebay_marketplace_questionnaires = st.session_state['ebay_marketplace_questionnaires']if session_ebay_marketplace_questionnaires == 'uploaded':count += 1self.payload += self.fetch_data("Marketplace Questionnaires - eBay")except Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")38 unmodified lines3940414243444546474822 unmodified lines717273747576777879808182832 unmodified lines8687888990915 unmodified lines97989910010110252 unmodified lines15515615715815916038 unmodified linesresponse.raise_for_status()output = response.json()#st.write(output)text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"]text = json.loads(text)#st.write(text)return textdef fetch_backlinks(self, data_field):mongodb_uri = os.getenv("MONGODB_URI")22 unmodified linesdef process (self):with st.spinner('Marketplace Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)debug_info = {'data_field' : 'Marketplace Analyst', 'result': payload_txt_model}upload_response(debug_info)st.session_state['product_title_amazon'] = ''st.session_state['images_amazon'] = ''st.session_state['bullet_points_amazon'] = ''2 unmodified linesst.session_state['category_ebay'] = ''st.session_state['images_ebay'] = ''st.session_state['product_description_ebay'] = ''count = 0except Exception as e:pass5 unmodified lines#analyze_button = st.button("Analyze", disabled=initialize_analyze_session())self.payload = ""count = 0try:session_product_title_amazon = st.session_state['product_title_amazon']if session_product_title_amazon == 'uploaded':52 unmodified linesself.payload += self.fetch_data("Product Description - eBay")except Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")
8 unmodified lines9101112131420 unmodified lines35363738394041424344454615 unmodified lines626364656667681 unmodified line7071727374757610 unmodified lines8788899091928 unmodified linesfrom helper.upload_File import uploadFilefrom helper.button_behaviour import hide_button, unhide_buttonfrom helper.initialize_analyze_session import initialize_analyze_sessionimport jsonfrom pymongo import MongoClientfrom helper.data_field import data_field20 unmodified linesresponse = requests.post(self.model_url, json=payload_txt, headers=headers)response.raise_for_status()output = response.json()#st.write(output)text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"]text = json.loads(text)#st.write(text)#backlinks = text[0]#referring_domains = text[1]return text15 unmodified linesdef process(self):with st.spinner('SEO Off Page Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)1 unmodified lineupload_response(debug_info)st.session_state['off_page_file_uploaded'] = ''except Exception as e:passst.session_state['analyzing'] = False10 unmodified linesexcept Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")self.payload = summary + self.payload8 unmodified lines91011121314151620 unmodified lines373839404142434445464715 unmodified lines636465666768691 unmodified line7172737475767710 unmodified lines888990919293948 unmodified linesfrom helper.upload_File import uploadFilefrom helper.button_behaviour import hide_button, unhide_buttonfrom helper.initialize_analyze_session import initialize_analyze_sessionimport pandas as pdimport asyncioimport jsonfrom pymongo import MongoClientfrom helper.data_field import data_field20 unmodified linesresponse = requests.post(self.model_url, json=payload_txt, headers=headers)response.raise_for_status()output = response.json()text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"]text = json.loads(text)backlinks = text[0]referring_domains = text[1]return text15 unmodified linesdef process(self):with st.spinner('SEO Off Page Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)1 unmodified lineupload_response(debug_info)st.session_state['off_page_file_uploaded'] = ''count = 0except Exception as e:passst.session_state['analyzing'] = False10 unmodified linesexcept Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")self.payload = summary + self.payload
73 unmodified lines7475767778798073 unmodified lineswith st.spinner('SEO On Page...', show_time=True):st.write('')# OUTPUT FOR SEO ANALYSTheaders = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)73 unmodified lines7475767778798073 unmodified lineswith st.spinner('SEO On Page...', show_time=True):st.write('')# OUTPUT FOR SEO ANALYSTheaders = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Pull through offers...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Pull through offers...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
78 unmodified lines7980818283848578 unmodified linesdef process (self):with st.spinner('SEM/PPC Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)78 unmodified lines7980818283848578 unmodified linesdef process (self):with st.spinner('SEM/PPC Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
59 unmodified lines6061626364656611 unmodified lines787980818283848586875 unmodified lines939495969798993 unmodified lines10310410510610710810911011111211311411511611711811912012112212359 unmodified linesmydb = myclient.get_database()mycol = mydb["df_data"]x = mycol.find_one({"data_field": data_field})x = x["result"]return xdef fetch_data(self, data_field):11 unmodified linesx = x["result"]return xdef process (self):with st.spinner('Seo Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)5 unmodified linesst.session_state['others'] = ''st.session_state['df_traffic'] = ''st.session_state['df_seo'] = ''except Exception as e:passst.session_state['analyzing'] = False3 unmodified lines#st.write("") # FOR THE HIDE BUTTON#analyze_button = st.button("Analyze", disabled=initialize_analyze_session())self.payload = ""self.payload += self.fetch_data("SEO Keywords")self.payload += self.fetch_data("Traffic Channels")self.payload += self.fetch_data("Traffic Acquisition")self.payload += self.fetch_data("Pages Indexed")self.payload += self.fetch_data("Bounce Rate")self.payload += self.fetch_backlinks("Backlinks")summary = self.fetch_data("Client Summary")self.payload = summary + self.payloadself.process()if __name__ == "__main__":59 unmodified lines6061626364656611 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551565 unmodified lines1621631641651661671683 unmodified lines17217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522659 unmodified linesmydb = myclient.get_database()mycol = mydb["df_data"]x = mycol.find_one({"data_field": data_field})x = x["result"]['question']return xdef fetch_data(self, data_field):11 unmodified linesx = x["result"]return xdef detect_encoding(self, uploaded_file):result = chardet.detect(uploaded_file.read(100000))uploaded_file.seek(0) # Reset file pointer to the beginningreturn result['encoding']def keyword_ranking(self, df_seo):keyword_ranking = df_seost.session_state['keyword_ranking'] = keyword_rankingkeywords_ranking_sorted = keyword_ranking.sort_values("Position", ascending=True)keywords_ranking_top_10 = keywords_ranking_sorted[keywords_ranking_sorted["Position"] <= 10].shape[0]keywords_ranking_top_100 = keywords_ranking_sorted[keywords_ranking_sorted["Position"] <= 100].shape[0]keyword_ranking = {'Keyword_top_10': keywords_ranking_top_10,'Keyword_top_100': keywords_ranking_top_100}st.session_state['keyword_ranking'] = keyword_rankingdef traffic_files(self, df_traffic):traffic_channels = df_traffictry:traffic_channels.rename(columns={traffic_channels.columns[0]: 'date'}, inplace=True)traffic_channels['date'] = pd.to_datetime(traffic_channels['date'], format='mixed')except pandas._libs.tslibs.parsing.DateParseError:passtraffic_channels_sort = traffic_channels.sort_values("date", ascending=False)organic_traffic = traffic_channels_sort['Organic Search'].values[0]paid_traffic = traffic_channels_sort['Paid Search'].values[0]direct_traffic = traffic_channels_sort['Direct'].values[0]referral_traffic = traffic_channels_sort['Referral'].values[0]st.session_state['organic_traffic'] = organic_trafficst.session_state['paid_traffic'] = paid_trafficst.session_state['direct_traffic'] = direct_trafficst.session_state['referral_traffic'] = referral_trafficdef ga4_traffic(self, others):st.session_state['others'] = othersga4_paid_social = others['Sessions'].values[0]ga4_organic_traffic = others['Sessions'].values[4]ga4_direct_traffic = others['Sessions'].values[2]ga4_referral_traffic = others['Sessions'].values[3]st.session_state['ga4_paid_social'] = ga4_paid_socialst.session_state['ga4_organic_traffic'] = ga4_organic_trafficst.session_state['ga4_direct_traffic'] = ga4_direct_trafficst.session_state['ga4_referral_traffic'] = ga4_referral_trafficdef delete_sessions(self):try:del st.session_state['df_traffic']del st.session_state['others']del st.session_state['df_seo']del st.session_state['keyword_ranking']del st.session_state['ga4_paid_social']del st.session_state['ga4_organic_traffic']del st.session_state['ga4_direct_traffic']del st.session_state['ga4_referral_traffic']del st.session_state['organic_traffic']del st.session_state['paid_traffic']del st.session_state['direct_traffic']del st.session_state['referral_traffic']except KeyError:passdef process (self):with st.spinner('Seo Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)5 unmodified linesst.session_state['others'] = ''st.session_state['df_traffic'] = ''st.session_state['df_seo'] = ''count = 0except Exception as e:passst.session_state['analyzing'] = False3 unmodified lines#st.write("") # FOR THE HIDE BUTTON#analyze_button = st.button("Analyze", disabled=initialize_analyze_session())self.payload = ""count = 0try:session_traffic_aqcuisition = st.session_state['df_seo']if session_traffic_aqcuisition == 'uploaded':count += 1self.payload += self.fetch_data("SEO Keywords")except Exception as e:passtry:session_traffic_channels = st.session_state['df_traffic']if session_traffic_channels == 'uploaded':count += 1self.payload += self.fetch_data("Traffic Channels")except Exception as e:passtry:session_others = st.session_state['others']if session_others == 'uploaded':count += 1self.payload += self.fetch_data("Traffic Acquisition")except Exception as e:passtry:session_page_index = st.session_state['pages_index']if session_page_index == 'uploaded':count += 1self.payload += self.fetch_data("Pages Indexed")except Exception as e:passtry:session_bounce_rate = st.session_state['bounce_rate']if session_bounce_rate == 'uploaded':count += 1self.payload += self.fetch_data("Bounce Rate")except Exception as e:passtry:session_backlinks = st.session_state["off_page_file_uploaded"]if session_backlinks == 'uploaded':self.payload += self.fetch_backlinks("Backlinks")except Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")self.payload = summary + self.payloadself.process()if __name__ == "__main__":
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientfrom helper.data_field import get_analyst_responseimport json
class Snapshot: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Snapshot...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Snapshot Analyst', 'result': payload_txt_model} upload_response(debug_info)
except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" self.website_and_tools_data = get_analyst_response("Website and Tools Analyst") self.sem_data = get_analyst_response("SEM/PPC Analyst") self.seo_data = get_analyst_response("SEO Analyst") self.social_media_data = get_analyst_response("Social Media Analyst") self.content_data = get_analyst_response("Content Analyst") self.marketpalce_data = get_analyst_response("Marketplace Analyst") analyst_data_dict = { "Website and Tools": self.website_and_tools_data, "SEM/PPC": self.sem_data, "SEO": self.seo_data, "Social Media": self.social_media_data, "Content": self.content_data, "Marketplace": self.marketpalce_data, }
for analyst_name, data in analyst_data_dict.items(): self.payload += f"\n\n--- {analyst_name} Analysis ---\n" if isinstance(data, list): self.payload += "\n".join(map(str, data)) else: self.payload += str(data) self.process() if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()79 unmodified lines8081828384858614 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212312412512612712879 unmodified linesdef process(self):with st.spinner('Social Media Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)14 unmodified linesdef row1(self):st.session_state['analyzing'] = Falseself.payload = ""self.payload += self.fetch_data("Facebook")self.payload += self.fetch_data("Instagram")self.payload += self.fetch_data("Twitter")self.payload += self.fetch_data("YouTube")self.payload += self.fetch_data("Linkedin")self.payload += self.fetch_data("Tiktok")summary = self.fetch_data("Client Summary")self.payload = summary + self.payloadself.process()if __name__ == "__main__":79 unmodified lines8081828384858614 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315479 unmodified linesdef process(self):with st.spinner('Social Media Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)14 unmodified linesdef row1(self):st.session_state['analyzing'] = Falseself.payload = ""count = 0try:session_fb = st.session_state['fb_upload']if session_fb == 'uploaded':count += 1self.payload += self.fetch_data("Facebook")except Exception as e:passtry:session_ig = st.session_state['ig_upload']if session_ig == 'uploaded':count += 1self.payload += self.fetch_data("Instagram")except Exception as e:passtry:session_twitter = st.session_state['twitter_upload']if session_twitter == 'uploaded':count += 1self.payload += self.fetch_data("Twitter")except Exception as e:passtry:session_yt = st.session_state['youtube_upload']if session_yt == 'uploaded':count += 1self.payload += self.fetch_data("YouTube")except Exception as e:passtry:session_linkedin = st.session_state['linkedin_upload']if session_linkedin == 'uploaded':count += 1self.payload += self.fetch_data("Linkedin")except Exception as e:passtry:session_tiktok = st.session_state['tiktok_upload']if session_tiktok == 'uploaded':count += 1self.payload += self.fetch_data("Tiktok")except Exception as e:passif count >= 1:summary = self.fetch_data("Client Summary")self.payload = summary + self.payloadself.process()if __name__ == "__main__":
54 unmodified lines5556575859606154 unmodified linesdef process(self):with st.spinner('Target Market Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)54 unmodified lines5556575859606154 unmodified linesdef process(self):with st.spinner('Target Market Analyst...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Website and Tools...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)71 unmodified lines7273747576777871 unmodified linesdef process(self):with st.spinner('Website and Tools...', show_time=True):st.write('')headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x-api-key')}"}try:payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"}payload_txt_model = self.request_model(payload_txt, headers)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import streamlit as stimport requestsfrom dotenv import load_dotenvimport osfrom helper.upload_response import upload_responsefrom helper.upload_File import uploadFilefrom pymongo import MongoClientimport json
class WebsiteAudienceAcquisition: def __init__(self, model_url): self.uploaded_files = [] self.file_dict = {} self.model_url = model_url #self.analyst_name = analyst_name #self.data_src = data_src #self.analyst_description = analyst_description self.initialize() self.row1()
def initialize(self): # FOR ENV load_dotenv()
# AGENT NAME #st.header(self.analyst_name) def request_model(self, payload_txt, headers): response = requests.post(self.model_url, json=payload_txt, headers=headers) response.raise_for_status() output = response.json() #st.write(output) text = output["outputs"][0]["outputs"][0]["results"]["text"]["data"]["text"] #text = json.loads(text) #st.write(text) return text def fetch_data(self, data_field): mongodb_uri = os.getenv("MONGODB_URI") myclient = MongoClient(mongodb_uri) mydb = myclient.get_database() mycol = mydb["df_data"] # Sort by timestamp field in descending order x = mycol.find_one( {"data_field": data_field}, sort=[("timestamp", -1)] ) x = x["result"] return x def process(self): with st.spinner('Website Audience Acquisition...', show_time=True): st.write('') headers = {"Content-Type": "application/json", "x-api-key": f"{os.getenv('x_api_key')}"} try: payload_txt = {"input_value": self.payload, "output_type": "text", "input_type": "chat"} payload_txt_model = self.request_model(payload_txt, headers) debug_info = {'data_field' : 'Website Audience Acquisition', 'result': payload_txt_model} upload_response(debug_info) st.session_state['website_audience'] = ''
count = 0 except Exception as e: pass st.session_state['analyzing'] = False def row1(self): st.session_state['analyzing'] = False self.payload = "" count = 0 try: session_content_outside_the_website = st.session_state['others'] if session_content_outside_the_website == 'uploaded': count += 1 self.payload += self.fetch_data("Traffic Acquisition") except Exception as e: pass if count >= 1: name = self.fetch_data("Client Name") website = self.fetch_data("Client Website") self.payload = name + website + self.payload self.process()
if __name__ == "__main__": st.set_page_config(layout="wide")
upload = uploadFile()55 unmodified lines5657585960616255 unmodified linesmobile_ads = ""video_ads = ""shopping_ads = ""with st.spinner('Uploading SEM/PPC...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"55 unmodified lines5657585960616255 unmodified linesmobile_ads = ""video_ads = ""shopping_ads = ""with st.spinner('Ads...', show_time=True):st.write('')# INITIALIZING SESSIONS#combined_text += f"Client Summary: {st.session_state.nature}\n"
69 unmodified lines7071727374757669 unmodified linesclient_relations_management_system = ""mobile_loading_speed = ""with st.spinner('Uploading Website and Tools...', show_time=True):st.write('')'''try:69 unmodified lines7071727374757669 unmodified linesclient_relations_management_system = ""mobile_loading_speed = ""with st.spinner('SEO On Page Analyst...', show_time=True):st.write('')'''try:
4 unmodified lines567891011121313 unmodified lines272829303132333435363738394041424344454647484950515253545556575859606162634 unmodified linesmyclient = MongoClient(mongodb_uri)mydb = myclient.get_database()mycol = mydb["df_data"]x = mycol.find_one({"data_field": data_src},sort=[('timestamp', -1)])x = x["result"]return xdef get_analyst_response(data_src):13 unmodified linesif myclient:myclient.close()def get_marketplace_response(data_src):try:mongodb_uri = os.getenv("MONGODB_URI")myclient = MongoClient(mongodb_uri)mydb = myclient.get_database()mycol = mydb["df_response"]# Find the most recent document matching the data_srcdocument = mycol.find_one({"data_field": data_src},sort=[('timestamp', -1)])# Check if document exists and has the result fieldif document and "result" in document:# Extract amazon and ebay data separatelyamazon_data = document["result"].get("amazon", [])ebay_data = document["result"].get("ebay", [])# Combine both datasets into a single listcombined_data = amazon_data + ebay_datareturn combined_dataelse:print(f"No matching document or 'result' field found for data_src: {data_src} in df_response. 404")return Noneexcept Exception as e:print(f"Error retrieving data: {str(e)}")return Nonefinally:if myclient:myclient.close()4 unmodified lines567891011121313 unmodified lines27282930314 unmodified linesmyclient = MongoClient(mongodb_uri)mydb = myclient.get_database()mycol = mydb["df_data"]x = mycol.find_one({"data_field": data_src})x = x["result"]["question"]#st.write(x)return xdef get_analyst_response(data_src):13 unmodified linesif myclient:myclient.close()#
38 unmodified lines394041424344454647484950515253545556575859606138 unmodified linesprint(f"Error sending data to MongoDB: {e}")finally:client.close()def clear_collection(data):"""Deletes all documents from a specified MongoDB collection."""mongodb_uri = os.getenv("MONGODB_URI")if not mongodb_uri:print("Deletion skipped: No database configured.")returntry:client = MongoClient(mongodb_uri)db = client.get_default_database()collection = db[f"{data}"] # Replace with your collection nameresult = collection.delete_many({})print(f"Deleted {result.deleted_count} documents from the collection.")except Exception as e:print(f"Error deleting documents: {e}")finally:client.close()38 unmodified lines39404138 unmodified linesprint(f"Error sending data to MongoDB: {e}")finally:client.close()
27 unmodified lines28293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747527 unmodified linespassst.session_state['uploaded_files'] = self.file_dictdef upload_website_audience(self, uploaded_files):for _ in range(len(self.file_dict)):self.file_dict.popitem()for uploaded_file in uploaded_files:if uploaded_file.type == "application/pdf":try:with pymupdf.open(stream=uploaded_file.read(), filetype="pdf") as doc:text = chr(12).join([page.get_text() for page in doc])self.file_dict[uploaded_file.name] = {'type': 'pdf', 'content': text}except Exception:passelif uploaded_file.type == "text/csv":try:# Skip comment lines that start with #df = pd.read_csv(uploaded_file,comment='#', # Treat lines starting with # as commentsengine='python' # Use more flexible engine)self.file_dict[uploaded_file.name] = {'type': 'csv', 'content': df}except Exception as e:print(f"Error processing CSV: {str(e)}")# If that fails, you could try a more manual approachtry:uploaded_file.seek(0)raw_text = uploaded_file.read().decode('utf-8')# Get only non-comment linesdata_lines = [line for line in raw_text.split('\n') if not line.strip().startswith('#')]# Use StringIO to create a file-like object from the filtered linesfrom io import StringIOcsv_data = StringIO('\n'.join(data_lines))# Read from the filtered datadf = pd.read_csv(csv_data)self.file_dict[uploaded_file.name] = {'type': 'csv', 'content': df}except Exception as e:print(f"Second attempt failed: {str(e)}")st.session_state['upload_website_audience'] = self.file_dictdef upload_file_seo(self, uploaded_files):for _ in range(len(self.file_dict)):27 unmodified lines28293031323327 unmodified linespassst.session_state['uploaded_files'] = self.file_dictdef upload_file_seo(self, uploaded_files):for _ in range(len(self.file_dict)):
12345676 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384import osimport streamlit as stimport threadingimport timefrom streamlit.runtime.scriptrunner import add_script_run_ctxfrom classes.response_off import SeoOffPageAnalystfrom classes.response_on_page import SeoOn6 unmodified linesfrom classes.response_sem_ppc import Sem_PPCfrom classes.response_marketplace import Marketplacefrom classes.response_target_market import TargetMarketfrom classes.response_df_overview import dfOverviewfrom classes.response_desired_outcome import DesiredOutcomefrom classes.response_conversion_analyst import ConversionAnalystfrom classes.response_website_audience_acquisition import WebsiteAudienceAcquisitionfrom classes.response_content_process_and_assets_analyst import Content_Process_and_Assets_Analystfrom classes.response_connection_analyst import ConnectionAnalystfrom classes.response_executive_summary import ExecutiveSummaryfrom classes.response_snapshot import Snapshot# Initialize session state to track if analysis has been runif 'analysis_completed' not in st.session_state:st.session_state.analysis_completed = False# Create a thread-safe way to update the UIclass ThreadSafeAnalysis:def __init__(self, placeholder, name):self.placeholder = placeholderself.name = nameself.lock = threading.Lock()def update_info(self, message):with self.lock:try:self.placeholder.info(message)except Exception:# Silently ignore errors here - this prevents "bad set index" errorspassdef update_success(self, message):with self.lock:try:self.placeholder.success(message)except Exception:# Silently ignore errors herepassdef update_error(self, message):with self.lock:try:self.placeholder.error(message)except Exception:# Silently ignore errors herepassdef run_analysis():# Create placeholders for status updatesplaceholders = {"off_page": st.empty(),"on_page": st.empty(),"website_tools": st.empty(),"seo": st.empty(),"social_media": st.empty(),"lld_pm_ln": st.empty(),"pull_through": st.empty(),"content": st.empty(),"sem_ppc": st.empty(),"marketplace": st.empty(),"target_market": st.empty(),"df_overview": st.empty(),"desired_outcome": st.empty(),"conversion": st.empty(),"website_audience": st.empty(),"content_process_and_assets": st.empty(),"connection": st.empty(),"snapshot": st.empty(),"executive_summary": st.empty(),}# Create thread-safe handlers for each analysis typehandlers = {name: ThreadSafeAnalysis(placeholder, name)for name, placeholder in placeholders.items()}# Define all analysis functionsdef run_off_page_analysis():handler = handlers["off_page"]try:handler.update_info("Running SEO Off Page Analysis...")result = SeoOffPageAnalyst(os.getenv('MODEL_Off_Page_Analyst'))handler.update_success("SEO Off Page Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"SEO Off Page Analysis failed: {str(e)}")return Nonedef run_on_page_analysis():handler = handlers["on_page"]try:handler.update_info("Running On Page Analysis...")result = SeoOn(os.getenv('MODEL_On_Page_Analyst'))handler.update_success("On Page Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"On Page Analysis failed: {str(e)}")return Nonedef run_website_and_tools_analysis():handler = handlers["website_tools"]try:handler.update_info("Running Website and Tools Analysis...")result = WebsiteAndTools(os.getenv('Model_Website_and_Tools_Analyst'))handler.update_success("Website and Tools completed successfully.")return resultexcept Exception as e:handler.update_error(f"Website and Tools Analysis failed: {str(e)}")return Nonedef run_seo_analysis():handler = handlers["seo"]try:handler.update_info("Running SEO Analysis...")result = Seo(os.getenv('MODEL_SEO_Analyst'))handler.update_success("SEO Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"SEO Analysis failed: {str(e)}")return Nonedef run_social_media_analysis():handler = handlers["social_media"]try:handler.update_info("Running Social Media Analysis...")result = SocialMedia(os.getenv('MODEL_Social_Media_Analyst'))handler.update_success("Social Media Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Social Media Analysis failed: {str(e)}")return Nonedef run_lld_pm_ln():handler = handlers["lld_pm_ln"]try:handler.update_info("Running LLD/PM/LN Analysis...")result = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))handler.update_success("LLD/PM/LN completed successfully.")return resultexcept Exception as e:handler.update_error(f"LLD/PM/LN Analysis failed: {str(e)}")return Nonedef run_pull_through_offers():handler = handlers["pull_through"]try:handler.update_info("Running Pull through offer Analysis...")result = PullThroughOffers(os.getenv('Model_Pull_Through_Offers_Analyst'))handler.update_success("Pull through offer completed successfully.")return resultexcept Exception as e:handler.update_error(f"Pull through offer Analysis failed: {str(e)}")return Nonedef run_content():handler = handlers["content"]try:handler.update_info("Running Content Analysis...")result = Content(os.getenv('Model_Content'))handler.update_success("Content Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Content Analysis failed: {str(e)}")return Nonedef run_sem_ppc_analysis():handler = handlers["sem_ppc"]try:handler.update_info("Running SEM/PPC Analysis...")result = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))handler.update_success("SEM/PPC Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"SEM/PPC Analysis failed: {str(e)}")return Nonedef run_marketplace_analysis():handler = handlers["marketplace"]try:handler.update_info("Running Marketplace Analysis...")result = Marketplace(os.getenv('Model_Marketplace_Analyst'))handler.update_success("Marketplace Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Marketplace Analysis failed: {str(e)}")return Nonedef run_target_market_analysis():handler = handlers["target_market"]try:handler.update_info("Running Target Market Analysis...")result = TargetMarket(os.getenv('Model_Target_Market_Analyst'))handler.update_success("Target Market Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Target Market Analysis failed: {str(e)}")return Nonedef run_df_overview_analysis():handler = handlers["df_overview"]try:handler.update_info("Running DF Overview Analysis...")result = dfOverview(os.getenv('Model_DF_Overview_Analyst'))handler.update_success("DF Overview Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"DF Overview Analysis failed: {str(e)}")return Nonedef run_desired_outcomes_analysis():handler = handlers["desired_outcome"]try:handler.update_info("Running Desired Outcomes Analysis...")result = DesiredOutcome(os.getenv('Model_Desired_Outcomes_DM_Analyst'))handler.update_success("Desired Outcomes Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Desired Outcomes Analysis failed: {str(e)}")return Nonedef run_conversion_analysis():handler = handlers["conversion"]try:handler.update_info("Running Conversion Analysis...")result = ConversionAnalyst(os.getenv('Model_Conversion_Analyst'))handler.update_success("Conversion Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Conversion Analysis failed: {str(e)}")return Nonedef run_website_audience():handler = handlers["website_audience"]try:handler.update_info("Running Website Audience Acquisition Analysis...")result = WebsiteAudienceAcquisition(os.getenv('Model_Website_Audience_Acquisition_Analyst'))handler.update_success("Website Audience Acquisition Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Website Audience Acquisition Analysis failed: {str(e)}")return Nonedef run_content_process_and_assets_analysis():handler = handlers["content_process_and_assets"]try:handler.update_info("Running Content - Process and Assets Analysis...")result = Content_Process_and_Assets_Analyst(os.getenv('Model_Content_Process_and_Assets_Analyst'))handler.update_success("Content - Process and Assets Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Content - Process and Assets Analysis failed: {str(e)}")return Nonedef run_connection_analysis():handler = handlers["connection"]try:handler.update_info("Connection Analysis...")result = ConnectionAnalyst(os.getenv('Model_Connection_Analyst'))handler.update_success("Connection Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Connection Analysis failed: {str(e)}")return Nonedef run_snapshot_analysis():handler = handlers["snapshot"]try:handler.update_info("Running Snapshot by Channel Analysis...")result = Snapshot(os.getenv('Model_Snapshot_by_Channel_Analyst'))handler.update_success("Snapshot by Channel Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Snapshot by Channel Analysis failed: {str(e)}")return Nonedef run_executive_summary_analysis():handler = handlers["executive_summary"]try:handler.update_info("Running Executive Summary Analysis...")result = ExecutiveSummary(os.getenv('Model_Executive_Summary_Analyst'))handler.update_success("Executive Summary Analysis completed successfully.")return resultexcept Exception as e:handler.update_error(f"Executive Summary Analysis failed: {str(e)}")return None# Define first batch of analysesthreads_first_batch = [(run_off_page_analysis, "off_page"),(run_on_page_analysis, "on_page"),(run_website_and_tools_analysis, "website_tools"),(run_seo_analysis, "seo"),(run_social_media_analysis, "social_media"),(run_lld_pm_ln, "lld_pm_ln"),(run_pull_through_offers, "pull_through"),(run_content, "content"),(run_sem_ppc_analysis, "sem_ppc"),#(run_marketplace_analysis, "marketplace"),(run_target_market_analysis, "target_market"),(run_df_overview_analysis, "df_overview"),(run_desired_outcomes_analysis, "desired_outcome"),(run_content_process_and_assets_analysis, "content_process_and_assets"),(run_conversion_analysis, "conversion"),(run_website_audience, "website_audience"),(run_connection_analysis, "connection")]# Create and start first batch threads with small delays to prevent UI conflictsthread_objects_first_batch = []for i, (func, name) in enumerate(threads_first_batch):# Add a small stagger to thread start times to reduce conflictstime.sleep(0.1)thread = threading.Thread(target=func, name=name)add_script_run_ctx(thread) # Attach Streamlit contextthread_objects_first_batch.append(thread)thread.start()# Wait for all first batch threads to completefor thread in thread_objects_first_batch:thread.join()# Add a separatortry:st.markdown("---")except Exception:pass# Wait a bit to let UI stabilize before starting second batchtime.sleep(0.5)# Create threads for second batch (snapshot and executive summary)threads_second_batch = [(run_snapshot_analysis, "snapshot"),(run_executive_summary_analysis, "executive_summary")]# Create and start second batch threadsthread_objects_second_batch = []for i, (func, name) in enumerate(threads_second_batch):# Add a small stagger between threadstime.sleep(0.2)thread = threading.Thread(target=func, name=name)add_script_run_ctx(thread) # Attach Streamlit contextthread_objects_second_batch.append(thread)thread.start()# Wait for second batch threads to completefor thread in thread_objects_second_batch:thread.join()# Set analysis_completed to True when all analyses are donest.session_state.analysis_completed = Truetry:st.success("🎉 All analyses completed!")except Exception:pass# Navigation buttonif st.button("Back"):st.switch_page("pages/home.py")# Main logicif not st.session_state.analysis_completed:run_analysis()else:st.info("Analysis has already been completed.")# View Results button (only displayed after analysis is completed)if st.session_state.analysis_completed and st.button("View Results", icon="📃"):st.switch_page("pages/output.py")st.session_state.analysis_completed = False1234566 unmodified lines131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import osimport streamlit as stimport threadingfrom streamlit.runtime.scriptrunner import add_script_run_ctxfrom classes.response_off import SeoOffPageAnalystfrom classes.response_on_page import SeoOn6 unmodified linesfrom classes.response_sem_ppc import Sem_PPCfrom classes.response_marketplace import Marketplacefrom classes.response_target_market import TargetMarketfrom classes.response_executive_summary import ExecutiveSummarydef run_analysis():# Placeholders for status updatesoff_page_status = st.empty()on_page_status = st.empty()website_and_tools_status = st.empty()seo_status = st.empty()social_media_status = st.empty()lld_pm_ln_status = st.empty()pull_through_offers_status = st.empty()content_status = st.empty()sem_ppc = st.empty()marketplace = st.empty()target_market = st.empty()executive_summary_status = st.empty()def run_off_page_analysis():try:off_page_status.info("Starting SEO Off Page Analysis...")result = SeoOffPageAnalyst(os.getenv('MODEL_Off_Page_Analyst'))off_page_status.success("SEO Off Page Analysis completed successfully.")return resultexcept Exception as e:off_page_status.error(f"SEO Off Page Analysis failed: {e}")return Nonedef run_on_page_analysis():try:on_page_status.info("Starting On Page Analysis...")result = SeoOn(os.getenv('MODEL_On_Page_Analyst'))on_page_status.success("On Page Analysis completed successfully.")return resultexcept Exception as e:on_page_status.error(f"On Page Analysis failed: {e}")return Nonedef run_website_and_tools_analysis():try:website_and_tools_status.info("Starting Website and Tools Analysis...")result = WebsiteAndTools(os.getenv('Model_Website_and_Tools_Analyst'))website_and_tools_status.success("Website and Tools completed successfully.")return resultexcept Exception as e:on_page_status.error(f"Website and Tools Analysis failed: {e}")return Nonedef run_seo_analysis():try:seo_status.info("Starting SEO Analysis...")result = Seo(os.getenv('MODEL_SEO_Analyst'))seo_status.success("SEO Analysis completed successfully.")return resultexcept Exception as e:seo_status.error(f"SEO Analysis failed: {e}")return Nonedef run_social_media_analysis():try:social_media_status.info("Starting Social Media Analysis...")result = SocialMedia(os.getenv('MODEL_Social_Media_Analyst'))social_media_status.success("Social Media Analysis completed successfully.")return resultexcept Exception as e:social_media_status.error(f"Social Media Analysis failed: {e}")return Nonedef run_lld_pm_ln():try:lld_pm_ln_status.info("Starting LLD/PM/LN Analysis...")result = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))lld_pm_ln_status.success("LLD/PM/LN completed successfully.")return resultexcept Exception as e:lld_pm_ln_status.error(f"LLD/PM/LN Analysis failed: {e}")return Nonedef run_pull_through_offers():try:pull_through_offers_status.info("Starting Pull through offer Analysis...")result = PullThroughOffers(os.getenv('Model_Pull_Through_Offers_Analyst'))pull_through_offers_status.success("Pull through offer completed successfully.")return resultexcept Exception as e:pull_through_offers_status.error(f"Pull through offer Analysis failed: {e}")return Nonedef run_content():try:content_status.info("Starting Content Analysis...")result = Content(os.getenv('Model_Content'))content_status.success("Content Analysis completed successfully.")return resultexcept Exception as e:content_status.error(f"Content Analysis failed: {e}")return Nonedef run_sem_ppc_analysis():try:sem_ppc.info("Starting SEM/PPC Analysis...")result = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))sem_ppc.success("SEM/PPC Analysis completed successfully.")return resultexcept Exception as e:sem_ppc.error(f"SEM/PPC Analysis failed: {e}")return Nonedef run_marketplace_analysis():try:marketplace.info("Starting Marketplace Analysis...")result = Marketplace(os.getenv('Model_SEM_PPC_Analyst'))marketplace.success("Marketplace Analysis completed successfully.")return resultexcept Exception as e:marketplace.error(f"Marketplace Analysis failed: {e}")return Nonedef run_target_market_analysis():try:target_market.info("Starting Target Market Analysis...")result = TargetMarket(os.getenv('Model_Target_Market_Analyst'))target_market.success("Target Market Analysis completed successfully.")return resultexcept Exception as e:target_market.error(f"Target Market Analysis failed: {e}")return Nonedef run_executive_summary_analysis():try:executive_summary = st.empty().info("Starting Executive Summary Analysis...")result = ExecutiveSummary(os.getenv('Model_Executive_Summary_Analyst'))executive_summary = st.empty().success("Executive Summary Analysis completed successfully.")return resultexcept Exception as e:executive_summary = st.empty().error(f"Executive Summary Analysis failed: {e}")return None# Create threads for concurrent executionoff_page_thread = threading.Thread(target=run_off_page_analysis)on_page_thread = threading.Thread(target=run_on_page_analysis)website_and_tools_thread = threading.Thread(target=run_website_and_tools_analysis)seo_thread = threading.Thread(target=run_seo_analysis)social_media_thread = threading.Thread(target=run_social_media_analysis)llm_pm_ln_thread = threading.Thread(target=run_lld_pm_ln)pull_through_offers_thread = threading.Thread(target=run_pull_through_offers)content_thread = threading.Thread(target=run_content)content_sem_ppc_thread = threading.Thread(target=run_sem_ppc_analysis)marketplace_thread = threading.Thread(target=run_marketplace_analysis)target_market_thread = threading.Thread(target=run_target_market_analysis)# Attach Streamlit context to threadsadd_script_run_ctx(off_page_thread)add_script_run_ctx(on_page_thread)add_script_run_ctx(website_and_tools_thread)add_script_run_ctx(seo_thread)add_script_run_ctx(social_media_thread)add_script_run_ctx(llm_pm_ln_thread)add_script_run_ctx(pull_through_offers_thread)add_script_run_ctx(content_thread)add_script_run_ctx(content_sem_ppc_thread)add_script_run_ctx(marketplace_thread)add_script_run_ctx(target_market_thread)# Start threadsoff_page_thread.start()on_page_thread.start()website_and_tools_thread.start()seo_thread.start()social_media_thread.start()llm_pm_ln_thread.start()pull_through_offers_thread.start()content_thread.start()content_sem_ppc_thread.start()marketplace_thread.start()target_market_thread.start()# Wait for threads to completeoff_page_thread.join()on_page_thread.join()website_and_tools_thread.join()seo_thread.join()social_media_thread.join()llm_pm_ln_thread.join()pull_through_offers_thread.join()content_thread.join()content_sem_ppc_thread.join()marketplace_thread.join()target_market_thread.join()st.markdown("---")executive_summary_status.info("Starting Executive Summary Analysis...")try:executive_summary = ExecutiveSummary(os.getenv('Model_Executive_Summary_Analyst'))executive_summary_status.success("Executive Summary Analysis completed successfully.")except Exception as e:executive_summary_status.error(f"Executive Summary Analysis failed: {e}")st.success("🎉 All analyses completed!") # Final success messagest.success("🎉 All analyses completed!") # Final success message# --- Display Button After Completion ---if st.button("View Results", icon="📃"):st.switch_page("pages/output.py")# Execute the analysisif st.button("Back"):st.switch_page("pages/home.py")run_analysis()
1 unmodified line2345672 unmodified lines101112131415162 unmodified lines1920212223242513 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777830 unmodified lines1091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481 unmodified lineimport streamlit as stfrom classes.Off_Page import SeoOffPageAnalystfrom classes.On_Page import SeoOnfrom classes.Seo import Seofrom classes.Social_Media_FB import Facebookfrom classes.Social_Media_IG import Instagram2 unmodified linesfrom classes.Linkedin import Linkedinfrom classes.Tiktok import Tiktokfrom classes.website_and_tools import WebsiteAndToolsfrom classes.client_summary import ClientSummaryfrom classes.pull_through_offers import PullThroughOffersfrom classes.lld_pm_ln import LLD_PM_LNfrom classes.content import Content2 unmodified linesfrom classes.ebay import eBayimport asynciofrom helper.upload_button import hide_button, unhide_buttonfrom helper.telemetry import clear_collectionimport timeclass DigitalFootprintDashboard:13 unmodified linesst.session_state['nature'] = ''if 'analyze' not in st.session_state:st.session_state['analyze'] = ''if 'analysis_completed' not in st.session_state:st.session_state.analysis_completed = Falseif 'uploading' not in st.session_state:st.session_state['uploading'] = Falseasync def create_row1(self):"""Create the first row with four columns"""col1, col2, col3, col4, col5 = st.columns(5, border=True, gap="medium", vertical_alignment="top")with col1:button_label = "Uploading..." if st.session_state['uploading'] else "Sync Data"if st.button(button_label, key="sync_button", icon="🔄", use_container_width=True):st.session_state['uploading'] = Truest.session_state['analyze'] = 'clicked'st.session_state['uploading'] = Falseelse:st.session_state["analyze"] = ''#self.upload_file_button = st.button("Sync Data", st.session_state['analyze'], icon="🔄", use_container_width=True)#if self.upload_file_button == True:# st.session_state["analyze"] = 'clicked'#unhide_button()#else:# st.session_state["analyze"] = ''analyze_disabled = st.session_state.get('analyze') != 'clicked'if st.button("Analyze", key="analyze_button", icon="✨", use_container_width=True, disabled=analyze_disabled):st.session_state.analysis_completed = Falsest.switch_page("pages/analyzing_page.py")self.client_summary = ClientSummary()with col2:st.write("## Website Traffic")30 unmodified linesself.website_and_tools = WebsiteAndTools(os.getenv('MODEL_On_Page_Analyst'))self.lld_pm_ln = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))self.pull_through_offers = PullThroughOffers(os.getenv('Model_Pull_Through_Offers_Analyst'))return col1, col2, col3, col4, col5async def create_row2(self):"""Create the first row with four columns"""col1, col4 = st.columns(2, border=True, gap="medium", vertical_alignment="top")# col1, col2, col3, col4 = st.columns(4, border=True, gap="medium", vertical_alignment="top")with col1:st.write("## Ads")self.sem_ppc = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))# with col2:# st.write("## Amazon")# self.amazon = Amazon(os.getenv('Model_SEM_PPC_Analyst'))# with col3:# st.write("## eBay")# self.ebay = eBay(os.getenv('Model_SEM_PPC_Analyst'))with col4:st.write("## Website Content")self.content = Content(os.getenv('Model_Content'))return col1, col4async def delete_button(self):reset_button = st.button("RESET ALL",icon="🗑️", use_container_width=True)if reset_button:clear_collection("df_data")clear_collection("df_response")async def main(self):"""Main method to run the dashboard"""await self.create_row1()await self.create_row2()await self.delete_button()#self.run_analysis()# Main execution1 unmodified line234567892 unmodified lines121314151617182 unmodified lines21222324252613 unmodified lines404142434445464748495051525354555657585960616263646566676830 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411 unmodified lineimport streamlit as stfrom classes.Off_Page import SeoOffPageAnalystfrom classes.On_Page import SeoOnfrom classes.On_Page_Crawl import SeoOnCrawlfrom classes.Seo_Backlinks import SeoBacklinksfrom classes.Seo import Seofrom classes.Social_Media_FB import Facebookfrom classes.Social_Media_IG import Instagram2 unmodified linesfrom classes.Linkedin import Linkedinfrom classes.Tiktok import Tiktokfrom classes.website_and_tools import WebsiteAndToolsfrom classes.client_summary import CientSummaryfrom classes.pull_through_offers import PullThroughOffersfrom classes.lld_pm_ln import LLD_PM_LNfrom classes.content import Content2 unmodified linesfrom classes.ebay import eBayimport asynciofrom helper.upload_button import hide_button, unhide_buttonimport timeclass DigitalFootprintDashboard:13 unmodified linesst.session_state['nature'] = ''if 'analyze' not in st.session_state:st.session_state['analyze'] = ''async def create_row1(self):"""Create the first row with four columns"""col1, col2, col3, col4, col5 = st.columns(5, border=True, gap="medium", vertical_alignment="top")with col1:self.upload_file_button = st.button("Sync Data", st.session_state['analyze'], icon="🔄", use_container_width=True)if self.upload_file_button == True:st.session_state["analyze"] = 'clicked'unhide_button()else:st.session_state["analyze"] = ''self.analyze_button = st.button("Analyze", icon="✨", use_container_width=True)if self.analyze_button == True:st.switch_page("pages/analyzing_page.py")else:hide_button()self.client_summary = CientSummary()with col2:st.write("## Website Traffic")30 unmodified linesself.website_and_tools = WebsiteAndTools(os.getenv('MODEL_On_Page_Analyst'))self.lld_pm_ln = LLD_PM_LN(os.getenv('Model_LLD_PM_LN_ANALYST'))self.pull_through_offers = PullThroughOffers(os.getenv('Model_Pull_Through_Offers_Analyst'))self.content = Content(os.getenv('Model_Content'))return col1, col2, col3, col4, col5async def create_row2(self):"""Create the first row with four columns"""col1, col2, col3, col4 = st.columns(4, border=True, gap="medium", vertical_alignment="top")with col1:st.write("## Ads")self.sem_ppc = Sem_PPC(os.getenv('Model_SEM_PPC_Analyst'))with col2:st.write("## Amazon")self.amazon = Amazon(os.getenv('Model_SEM_PPC_Analyst'))with col3:st.write("## eBay")self.ebay = eBay(os.getenv('Model_SEM_PPC_Analyst'))return col1, col2, col3async def run_analysis(self):result = await asyncio.gather(self.gtmetrix.process(),self.backlinks.process(),self.keywords.process(),self.facebook.process(),self.instagram.process(),self.twitter.process(),self.youtube.process(),self.linkedin.process(),self.tiktok.process(),)st.session_state.analyze = Falseasync def main(self):"""Main method to run the dashboard"""await self.create_row1()await self.create_row2()#self.run_analysis()# Main execution
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511616 unmodified lines13313413513613713813979 unmodified lines21922022122222322422522622722822923023123223323423523623723823924011 unmodified lines2522532542552562572585 unmodified lines2642652662672682692705 unmodified lines2762772782792802812824 unmodified lines2872882892902912922931 unmodified line2952962972982993003013023033043053063073083094 unmodified lines3143153163173183193201 unmodified line32232332432532632732832933033133233333433513 unmodified lines3493503513523533543551 unmodified line3573583593603613623637 unmodified lines3713723733743753763771 unmodified line3793803813823833843853863873883893903913923933943953963973983993 unmodified lines403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448import jsonimport osimport streamlit as stfrom helper.data_field import get_analyst_response, data_field, get_marketplace_responseimport timest.set_page_config(layout="centered")def write_client_footprint():try:web = get_analyst_response("Website and Tools Analyst")result_web = {item["category"]: item["current_footprint"] for item in web}except TypeError:result_web = Nonetry:seo = get_analyst_response("SEO Analyst")seo = {item["category"]: item["current_footprint"] for item in seo}except TypeError:seo = Nonetry:socmed = get_analyst_response("Social Media Analyst")socmed = {item["category"]: item["current_footprint"] for item in socmed}except TypeError:socmed = Nonedef safe_get(data, key):value = data.get(key)return value if value else "N/A"markdown_table = "| Source/Channel | Current KPI |\n"markdown_table += "|---|---|\n"markdown_table += f"| Website Health Score | {safe_get(result_web, 'website_overall_health_score')} |\n"markdown_table += f"| Organic Traffic to the Website | {safe_get(seo, 'organic_traffic')} |\n"markdown_table += f"| Paid Traffic to the Website | {safe_get(seo, 'paid_traffic')} |\n"markdown_table += f"| Referral Traffic to the Website | {safe_get(seo, 'referral_traffic')} |\n"markdown_table += f"| Email Traffic to the Website | N/A |\n"markdown_table += f"| Direct Traffic to the Website | {safe_get(seo, 'direct_traffic')} |\n"markdown_table += f"| Social Traffic to the Website | N/A |\n"markdown_table += f"| Display Traffic to the Website | N/A |\n"markdown_table += f"| Email Database | N/A |\n"markdown_table += f"| Facebook Followers | {safe_get(socmed, 'facebook_followers')} |\n"markdown_table += f"| Twitter Followers | {safe_get(socmed, 'twitter_followers')} |\n"markdown_table += f"| Instagram Followers | {safe_get(socmed, 'instagram_followers')} |\n"markdown_table += f"| Linkedin Followers | {safe_get(socmed, 'linkedin_followers')} |\n"markdown_table += f"| Google My Business | N/A |\n"markdown_table += f"| # of Keywords Ranking in Top 10 | {safe_get(seo, 'keyword_ranking_in_top_10')} |\n"markdown_table += f"| # of Keywords Ranking in Top 100 | {safe_get(seo, 'keyword_ranking_in_top_100')} |\n"return markdown_tabledef write_snapshot(data):if data:try:parsed_data = dataif isinstance(parsed_data, list):# Create Markdown table headermarkdown_table = "| Channel | Status | Requirements | What's Needed to Deliver |\n"markdown_table += "|---|---|---|---|\n"# Loop through the list of dictionariesfor item in parsed_data:# Use .get() for safety in case keys are missingchannel = item.get('channel', 'N/A')status = item.get('status', 'N/A')requirements = item.get('requirements', 'N/A')deliver = item.get('deliver', 'N/A')# Add a row to the Markdown table string# Replace underscores with spaces and apply title case to category# Replace underscores with spaces firstchannel_temp = channel.replace('_', ' ')# Apply title case if there are multiple words, otherwise uppercaseif ' ' in channel_temp: # Check for spaces directlychannel_formatted = channel_temp.title()else:channel_formatted = channel_temp.upper() # Use upper() instead of upper_case()markdown_table += f"| {channel_formatted} | {status} | {requirements} | {deliver} |\n"# Display the complete Markdown tablest.markdown(markdown_table)# Handle case if data is not a list (e.g., a single dictionary)elif isinstance(parsed_data, dict):st.write("Analysis Result (Summary):")# You might want to display dictionary data differentlyst.json(parsed_data) # Example: Display as JSONelse:st.warning("data is not in the expected list format.")st.write(parsed_data) # Show the raw dataexcept json.JSONDecodeError:st.error("Error: Could not parse the data as JSON.")st.text(data) # Show the raw string dataexcept AttributeError:st.error("Error: Could not find expected keys ('channel', 'status', 'requirements', 'deliver') in the data.")st.write(parsed_data) # Show the data that caused the errorexcept Exception as e:st.error(f"An unexpected error occurred while processing data: {e}")st.write(data) # Show the raw dataelse:st.warning("No data retrieved for analysis.")# --- End: Loop and display data ---def write_table(website_and_tools_data):if website_and_tools_data:16 unmodified lines# Add a row to the Markdown table string# Replace underscores with spaces and apply title case to categorycategory_formatted = category.replace('_', ' ').title()current_footprint_formatted = current_footprint.replace('_', ' ')best_of_breed_formatted = best_of_breed.replace('_', ' ')79 unmodified lines# --- End: Loop and display data ---def display_outputs():client_name = data_field("Client Name")client_website = data_field("Client Website")overview = get_analyst_response("DF Overview Analyst")st.markdown("# Digital Marketing Audit")st.markdown(f"for: **{client_name} ({client_website})**")st.write("")st.markdown("### DIGITAL FOOTPRINT OVERVIEW")st.markdown(f"{overview}")st.markdown("---")st.markdown("### Executive Summary")st.markdown(get_analyst_response("Executive Summary"))st.markdown("---")st.markdown("### CLIENT FOOTPRINT")11 unmodified linesst.markdown("---")st.markdown("### SNAPSHOT BY CHANNEL")write_snapshot(get_analyst_response("Snapshot Analyst")) #write_snapshotst.markdown("---")st.markdown("## AUDITS PER CHANNEL")5 unmodified lineswebsite_and_tools_data = get_analyst_response("Website and Tools Analyst")write_table(website_and_tools_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")st.markdown("### SEARCH ENGINE MARKETING/PPC")5 unmodified linessem_data = get_analyst_response("SEM/PPC Analyst")write_table(sem_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")st.markdown("### SEARCH ENGINE OPTIMIZATION")4 unmodified linesseo_data = get_analyst_response("SEO Analyst")write_table(seo_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write On Page Table1 unmodified lineon_page_data = get_analyst_response("On Page Analyst")seo_on_page_table(on_page_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write Off Page Tablest.markdown("### OFF PAGE OPTIMIZATION")on_page_data = get_analyst_response("SEO Off Page Analyst")seo_on_page_table(on_page_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write SocMed Table4 unmodified linessocial_media_data = get_analyst_response("Social Media Analyst")write_table(social_media_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write SocMed Table1 unmodified linest.markdown(f"""Content is king in digital marketing. People log into the internet to look for and consume information in different formats: text-based, video, audio, or image. Content is what help businesses establish their expertise in the industry, convert leads into customers, guide their customers through their sales funnel, and build relationships with their customers. """)content_data = get_analyst_response("Content Analyst")write_table(content_data)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# if (get_analyst_response("Marketplace Analyst")):# st.markdown("### MARKET PLACE")# st.table(get_analyst_response("Marketplace Analyst"))# st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)# st.markdown("---")st.markdown("## OTHER INFORMATION")13 unmodified linesst.write(target_market_data['summary'])st.markdown("##### WHAT IS THE DESIRED OUTCOMES OF DIGITAL MARKETING?")st.markdown(get_analyst_response("Desired Outcomes Analyst"))st.markdown("##### WHAT IS THE PULL-THROUGH OFFER?")pull_through_data = get_analyst_response("Pull through offers Analyst")1 unmodified linest.markdown("##### WEBSITE AUDIENCE ACQUISITION")website_audience_data = get_analyst_response("Website Audience Acquisition")st.write(website_audience_data)#LLD/PM/LN7 unmodified linesst.markdown("##### LEAD NURTURING")st.write(lld_data.get('lead_nurturing', None))#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")1 unmodified linest.write(f"""Content is king in digital marketing. People log into the internet to look for and consume information in different formats: text-based, video, audio, or image. Content is what help businesses establish their expertise in the industry, convert leads into customers, guide their customers through their sales funnel, and build relationships with their customers. \nWe have evaluated the process of content development strategy and existing content assets of {client_name} based on how they serve clients throughout the customer journey. """)def safe_value(data: dict, key: str) -> str:try:value = data.get(key)return value if value else "N/A"except Exception:return "N/A"pna_data = get_analyst_response("Content - Process and Assets Analyst")if pna_data:st.markdown("##### AWARENESS STAGE")st.write(safe_value(pna_data, 'awareness_stage'))st.markdown("##### CONSIDERATION STAGE")st.write(safe_value(pna_data, 'consideration_stage'))st.markdown("##### DECISION STAGE")st.write(safe_value(pna_data, 'decision_stage'))else:st.markdown("##### AWARENESS STAGE")3 unmodified linesst.markdown("##### DECISION STAGE")st.write(None)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")conversion = get_analyst_response("Conversion Analyst")st.markdown("#### CONVERSION – ACTIVATION OF VISITORS")if conversion:st.markdown("##### AWARENESS TO TRAFFIC")st.write(safe_value(conversion, 'awareness_to_traffic'))st.markdown("##### TRAFFIC TO LEAD CONVERSION")st.write(safe_value(conversion, 'traffic_to_lead'))st.markdown("##### LEAD TO SALES CONVERSION")st.write(safe_value(conversion, 'lead_to_sales'))st.markdown("##### CONVERSION TO BRAND LOYALTY")st.write(safe_value(conversion, 'conversion_to_brand'))else:st.markdown("##### AWARENESS TO TRAFFIC")st.write(None)st.markdown("##### TRAFFIC TO LEAD CONVERSION")st.write(None)st.markdown("##### LEAD TO SALES CONVERSION")st.write(None)st.markdown("##### CONVERSION TO BRAND LOYALTY")st.write(None)conversion = get_analyst_response("Connection Analyst")st.markdown("##### CONNECTION OF ALL ONLINE AND OFFLINE TOUCH POINTS")st.write(conversion)#st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("<div id='top'></div>", unsafe_allow_html=True);if st.button("Back to Dashboard", icon="🏠"):st.switch_page("pages/home.py")display_outputs()12345678910111213141516171819202122232425262728293031323334353637383940414243444516 unmodified lines62636465666779 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017111 unmodified lines1831841851861871881895 unmodified lines1951961971981992002015 unmodified lines2072082092102112122134 unmodified lines2182192202212222232241 unmodified line2262272282292302312322332342352362372382392404 unmodified lines2452462472482492502511 unmodified line25325425525625725825926026126226326426526626713 unmodified lines2812822832842852862871 unmodified line2892902912922932942957 unmodified lines3033043053063073083091 unmodified line3113123133143153163173183193203213223233243253 unmodified lines329330331332333334335336337338339340341342343344345346347348349350351352import jsonimport osimport streamlit as stfrom helper.data_field import get_analyst_responsefrom helper.telemetry import collect_telemetryst.set_page_config(layout="centered")def write_client_footprint():web = get_analyst_response("Website and Tools Analyst")result_web = {item["category"]: item["current_footprint"] for item in web}seo = get_analyst_response("SEO Analyst")seo = {item["category"]: item["current_footprint"] for item in seo}socmed = get_analyst_response("Social Media Analyst")socmed = {item["category"]: item["current_footprint"] for item in socmed}markdown_table = "| Source/Channel | Current KPI |\n"markdown_table += "|---|---|\n"markdown_table += f"| Website Health Score | {result_web['website_overall_health_score']} |\n"markdown_table += f"| Organic Traffic to the Website | {seo['organic_traffic']} |\n"markdown_table += f"| Paid Traffic to the Website | {seo['paid_traffic']} |\n"markdown_table += f"| Referral Traffic to the Website | {seo['referral_traffic']} |\n"markdown_table += f"| Email Traffic to the Website | N/A |\n"markdown_table += f"| Direct Traffic to the Website | {seo['direct_traffic']} |\n"markdown_table += f"| Social Traffic to the Website | N/A |\n"markdown_table += f"| Display Traffic to the Website | N/A |\n"markdown_table += f"| Email Database | N/A |\n"markdown_table += f"| Facebook Followers | {socmed['facebook_followers']} |\n"markdown_table += f"| Twitter Followers | {socmed['twitter_followers']} |\n"markdown_table += f"| Instagram Followers | {socmed['instagram_followers']} |\n"markdown_table += f"| Linkedin Followers | {socmed['linkedin_followers']} |\n"markdown_table += f"| Google My Business | N/A |\n"markdown_table += f"| # of Keywords Ranking in Top 10 | {seo['keyword_ranking_in_top_10']} |\n"markdown_table += f"| # of Keywords Ranking in Top 100 | {seo['keyword_ranking_in_top_100']} |\n"return markdown_tabledef write_table(website_and_tools_data):if website_and_tools_data:16 unmodified lines# Add a row to the Markdown table string# Replace underscores with spaces and apply title case to categorycategory_formatted = category.replace('_', ' ').title()current_footprint_formatted = current_footprint.replace('_', ' ')best_of_breed_formatted = best_of_breed.replace('_', ' ')79 unmodified lines# --- End: Loop and display data ---def display_outputs():st.markdown("<div id='top'></div>", unsafe_allow_html=True);client_name = "RMX Creatives"client_website = "https://rmxcreatives.com/"overview = f"""**{client_name}** is a financial services company based in Auckland, New Zealand, specializing in providing quick and flexible loan solutions for businesses and individuals. Represented by Paul Stone, LoansOne has enlisted ShoreMarketing to perform a deep dive into their digital footprint to have a view of the holistic status of their digital properties and determine how each property can play part in implementing a stronger digital marketing plan.\nThe Digital Marketing Footprint consists of deep-dive research by ShoreMarketing specialists to help the business leaders of LoansOne understand the effectiveness of their existing digital initiatives with the view of giving them an insight to developing a strategy and effectively allocating business resources to digital properties that will give them the best results.\nThis document represents the results of our audit of LoansOne’s digital marketing and management practices. Our audit covered reviews of key digital areas: Website and Tools, PPC/SEM, SEO, Social Media, and Market Places."""st.markdown("# Digital Marketing Audit")st.markdown(f"for: **{client_name} ({client_website})**")st.write("")st.write("")st.write("")st.markdown("### DIGITAL FOOTPRINT OVERVIEW")st.markdown(f"{overview}")st.markdown("---")st.markdown("### Executive Summary")st.markdown(f"Simtech LED's digital footprint reveals significant strengths and areas for improvement that can enhance its competitive positioning in the casino, gaming, and entertainment LED market. The analysis highlights the following key findings and recommendations")st.markdown("---")st.markdown("### CLIENT FOOTPRINT")11 unmodified linesst.markdown("---")st.markdown("### SNAPSHOT BY CHANNEL")st.write("TBD")st.markdown("---")st.markdown("## AUDITS PER CHANNEL")5 unmodified lineswebsite_and_tools_data = get_analyst_response("Website and Tools Analyst")write_table(website_and_tools_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")st.markdown("### SEARCH ENGINE MARKETING/PPC")5 unmodified linessem_data = get_analyst_response("SEM/PPC Analyst")write_table(sem_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")st.markdown("### SEARCH ENGINE OPTIMIZATION")4 unmodified linesseo_data = get_analyst_response("SEO Analyst")write_table(seo_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write On Page Table1 unmodified lineon_page_data = get_analyst_response("On Page Analyst")seo_on_page_table(on_page_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write Off Page Tablest.markdown("### OFF PAGE OPTIMIZATION")on_page_data = get_analyst_response("Off Page Analyst")seo_on_page_table(on_page_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write SocMed Table4 unmodified linessocial_media_data = get_analyst_response("Social Media Analyst")write_table(social_media_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")# Write SocMed Table1 unmodified linest.markdown(f"""Content is king in digital marketing. People log into the internet to look for and consume information in different formats: text-based, video, audio, or image. Content is what help businesses establish their expertise in the industry, convert leads into customers, guide their customers through their sales funnel, and build relationships with their customers. """)content_data = get_analyst_response("Content Analyst")write_table(content_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")if (get_analyst_response("Marketplace Analyst")):st.markdown("### MARKET PLACE")marketpalce_data = get_analyst_response("Marketplace Analyst")write_table(marketpalce_data)st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")st.markdown("## OTHER INFORMATION")13 unmodified linesst.write(target_market_data['summary'])st.markdown("##### WHAT IS THE DESIRED OUTCOMES OF DIGITAL MARKETING?")st.write("TBD")st.markdown("##### WHAT IS THE PULL-THROUGH OFFER?")pull_through_data = get_analyst_response("Pull through offers Analyst")1 unmodified linest.markdown("##### WEBSITE AUDIENCE ACQUISITION")website_audience_data = get_analyst_response("Website Audience Acquisition Analyst")st.write(website_audience_data)#LLD/PM/LN7 unmodified linesst.markdown("##### LEAD NURTURING")st.write(lld_data.get('lead_nurturing', None))st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("---")1 unmodified linest.write(f"""Content is king in digital marketing. People log into the internet to look for and consume information in different formats: text-based, video, audio, or image. Content is what help businesses establish their expertise in the industry, convert leads into customers, guide their customers through their sales funnel, and build relationships with their customers. \nWe have evaluated the process of content development strategy and existing content assets of {client_name} based on how they serve clients throughout the customer journey. """)pna_data = get_analyst_response("Content - Process and Assets Analyst")if pna_data:st.markdown("##### AWARENESS STAGE")st.write(pna_data.get('awareness_stage', 'N/A'))st.markdown("##### CONSIDERATION STAGE")st.write(pna_data.get('consideration_stage', 'N/A'))st.markdown("##### DECISION STAGE")st.write(pna_data.get('decision_stage', 'N/A'))else:st.markdown("##### AWARENESS STAGE")3 unmodified linesst.markdown("##### DECISION STAGE")st.write(None)st.markdown("---")st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)st.markdown("#### CONVERSION – ACTIVATION OF VISITORS")st.markdown("##### AWARENESS TO TRAFFIC")st.write("TBD")st.markdown("##### TRAFFIC TO LEAD CONVERSION")st.write("TBD")st.markdown("##### LEAD TO SALES CONVERSION")st.write("TBD")st.markdown("##### CONVERSION TO BRAND LOYALTY")st.write("TBD")st.markdown("##### CONNECTION OF ALL ONLINE AND OFFLINE TOUCH POINTS")st.write("TBD")st.markdown("<a href='#top'>Go to top</a>", unsafe_allow_html=True)if st.button("Back to Dashboard", icon="🏠"):st.switch_page("pages/home.py")display_outputs()
classes/Linkedin.py+1-1
classes/Off_Page.py+30-72
classes/On_Page.py+1-3
classes/On_Page_Crawl.py+1-1
classes/Seo.py+52-16
classes/Seo_Backlinks.py+1-1
classes/Social_Media_FB.py+1-1
classes/Social_Media_IG.py+1-1
classes/Tiktok.py+1-1
classes/Twitter.py+1-1
classes/Youtube.py+1-1
classes/amazon.py+15-59
classes/client_summary.py+7-7
classes/content.py+9-98
classes/ebay.py+17-60
classes/lld_pm_ln.py+1-1
classes/pull_through_offers.py+1-1
classes/response_connection_analyst.pyDeleted-87
classes/response_content.py+1-1
classes/response_content_process_and_assets_analyst.pyDeleted-100
classes/response_conversion_analyst.pyDeleted-118
classes/response_desired_outcome.pyDeleted-88
classes/response_df_overview.pyDeleted-95
classes/response_executive_summary.py+3-1
classes/response_lld_pm_ln.py+1-1
classes/response_marketplace.py+6-29
classes/response_off.py+8-6
classes/response_on_page.py+1-1
classes/response_pull_through_offers.py+1-1
classes/response_sem_ppc.py+1-1
classes/response_seo.py+120-17
classes/response_snapshot.pyDeleted-101
classes/response_social_media.py+49-23
classes/response_target_market.py+1-1
classes/response_website_and_tools.py+1-1
classes/response_website_audience_acquisition.pyDeleted-91
classes/sem_ppc.py+1-1
classes/website_and_tools.py+1-1
helper/data_field.py+4-36
helper/telemetry.py-20
helper/upload_File.py-42
pages/analyzing_page.py+117-279
pages/home.py+36-43
pages/output.py+66-162