forked from CharlyWargnier/google-search-console-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_app.py
879 lines (722 loc) · 34 KB
/
streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# basic imports
import asyncio
import streamlit as st
import pandas as pd
# imports for search console libraries
import searchconsole
from apiclient import discovery
from google_auth_oauthlib.flow import Flow
# imports for aggrid
from st_aggrid import AgGrid
from st_aggrid import AgGrid
from st_aggrid.grid_options_builder import GridOptionsBuilder
from st_aggrid.shared import JsCode
from st_aggrid import GridUpdateMode, DataReturnMode
# all other imports
import os
from streamlit_elements import Elements
###############################################################################
# The code below is for the layout of the page
if "widen" not in st.session_state:
layout = "centered"
else:
layout = "wide" if st.session_state.widen else "centered"
st.set_page_config(
layout=layout, page_title="Google Search Console Connector", page_icon="🔌"
)
###############################################################################
# row limit
RowCap = 25000
###############################################################################
tab1, tab2 = st.tabs(["Main", "About"])
with tab1:
st.sidebar.image("logo.png", width=290)
st.sidebar.markdown("")
st.write("")
# Convert secrets from the TOML file to strings
clientSecret = str(st.secrets["installed"]["client_secret"])
clientId = str(st.secrets["installed"]["client_id"])
redirectUri = str(st.secrets["installed"]["redirect_uris"][0])
st.markdown("")
if "my_token_input" not in st.session_state:
st.session_state["my_token_input"] = ""
if "my_token_received" not in st.session_state:
st.session_state["my_token_received"] = False
def charly_form_callback():
# st.write(st.session_state.my_token_input)
st.session_state.my_token_received = True
code = st.experimental_get_query_params()["code"][0]
st.session_state.my_token_input = code
with st.sidebar.form(key="my_form"):
st.markdown("")
mt = Elements()
mt.button(
"Sign-in with Google",
target="_blank",
size="large",
variant="contained",
start_icon=mt.icons.exit_to_app,
onclick="none",
style={"color": "#FFFFFF", "background": "#FF4B4B"},
href="https://accounts.google.com/o/oauth2/auth?response_type=code&client_id="
+ clientId
+ "&redirect_uri="
+ redirectUri
+ "&scope=https://www.googleapis.com/auth/webmasters.readonly&access_type=offline&prompt=consent",
)
mt.show(key="687")
credentials = {
"installed": {
"client_id": clientId,
"client_secret": clientSecret,
"redirect_uris": [],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
}
}
flow = Flow.from_client_config(
credentials,
scopes=["https://www.googleapis.com/auth/webmasters.readonly"],
redirect_uri=redirectUri,
)
auth_url, _ = flow.authorization_url(prompt="consent")
submit_button = st.form_submit_button(
label="Access GSC API", on_click=charly_form_callback
)
st.write("")
with st.expander("How to access your GSC data?"):
st.markdown(
"""
1. Click on the `Sign-in with Google` button
2. You will be redirected to the Google Oauth screen
3. Choose the Google account you want to use & click `Continue`
5. You will be redirected back to this app.
6. Click on the "Access GSC API" button.
7. Voilà! 🙌
"""
)
st.write("")
with st.expander("Check your Oauth token"):
code = st.text_input(
"",
key="my_token_input",
label_visibility="collapsed",
)
st.write("")
container3 = st.sidebar.container()
st.sidebar.write("")
st.sidebar.caption(
"Made in 🎈 [Streamlit](https://www.streamlit.io/), by [Charly Wargnier](https://www.charlywargnier.com/)."
)
try:
if st.session_state.my_token_received == False:
with st.form(key="my_form2"):
# text_input_container = st.empty()
webpropertiesNEW = st.text_input(
"Web property to review (please sign in via Google OAuth first)",
value="",
disabled=True,
)
filename = webpropertiesNEW.replace("https://www.", "")
filename = filename.replace("http://www.", "")
filename = filename.replace(".", "")
filename = filename.replace("/", "")
col1, col2, col3 = st.columns(3)
with col1:
dimension = st.selectbox(
"Dimension",
(
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose a top dimension",
)
with col2:
nested_dimension = st.selectbox(
"Nested dimension",
(
"none",
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose a nested dimension",
)
with col3:
nested_dimension_2 = st.selectbox(
"Nested dimension 2",
(
"none",
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose a second nested dimension",
)
st.write("")
col1, col2 = st.columns(2)
with col1:
search_type = st.selectbox(
"Search type",
("web", "video", "image", "news", "googleNews"),
help="""
Specify the search type you want to retrieve
- **Web**: Results that appear in the All tab. This includes any image or video results shown in the All results tab.
- **Image**: Results that appear in the Images search results tab.
- **Video**: Results that appear in the Videos search results tab.
- **News**: Results that show in the News search results tab.
""",
)
with col2:
timescale = st.selectbox(
"Date range",
(
"Last 7 days",
"Last 30 days",
"Last 3 months",
"Last 6 months",
"Last 12 months",
"Last 16 months",
),
index=0,
help="Specify the date range",
)
if timescale == "Last 7 days":
timescale = -7
elif timescale == "Last 30 days":
timescale = -30
elif timescale == "Last 3 months":
timescale = -91
elif timescale == "Last 6 months":
timescale = -182
elif timescale == "Last 12 months":
timescale = -365
elif timescale == "Last 16 months":
timescale = -486
st.write("")
with st.expander("✨ Advanced Filters", expanded=False):
col1, col2, col3 = st.columns(3)
with col1:
filter_page_or_query = st.selectbox(
"Dimension to filter #1",
("query", "page", "device", "searchAppearance", "country"),
help="""
You can choose to filter dimensions and apply filters before executing a query.
""",
)
with col2:
filter_type = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
help="""
Note that if you use Regex in your filter, you must follow the `RE2` syntax.
""",
)
with col3:
filter_keyword = st.text_input(
"Keyword(s) to filter ",
"",
help="Add the keyword(s) you want to filter",
)
with col1:
filter_page_or_query2 = st.selectbox(
"Dimension to filter #2",
("query", "page", "device", "searchAppearance", "country"),
key="filter_page_or_query2",
help="""
You can choose to filter dimensions and apply filters before executing a query.
""",
)
with col2:
filter_type2 = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
key="filter_type2",
help="""
Note that if you use Regex in your filter, you must follow the `RE2` syntax.
""",
)
with col3:
filter_keyword2 = st.text_input(
"Keyword(s) to filter ",
"",
key="filter_keyword2",
help="Add the keyword(s) you want to filter",
)
with col1:
filter_page_or_query3 = st.selectbox(
"Dimension to filter #3",
("query", "page", "device", "searchAppearance", "country"),
key="filter_page_or_query3",
help="""
You can choose to filter dimensions and apply filters before executing a query.
""",
)
with col2:
filter_type3 = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
key="filter_type3",
help="""
Note that if you use Regex in your filter, you must follow the `RE2` syntax.
""",
)
with col3:
filter_keyword3 = st.text_input(
"Keyword(s) to filter ",
"",
key="filter_keyword3",
help="Add the keyword(s) you want to filter",
)
st.write("")
submit_button = st.form_submit_button(
label="Fetch GSC API data", on_click=charly_form_callback
)
if (nested_dimension != "none") and (nested_dimension_2 != "none"):
if (
(dimension == nested_dimension)
or (dimension == nested_dimension_2)
or (nested_dimension == nested_dimension_2)
):
st.warning(
"🚨 Dimension and nested dimensions cannot be the same, please make sure you choose unique dimensions."
)
st.stop()
else:
pass
elif (nested_dimension != "none") and (nested_dimension_2 == "none"):
if dimension == nested_dimension:
st.warning(
"🚨 Dimension and nested dimensions cannot be the same, please make sure you choose unique dimensions."
)
st.stop()
else:
pass
else:
pass
if st.session_state.my_token_received == True:
@st.experimental_singleton
def get_account_site_list_and_webproperty(token):
flow.fetch_token(code=token)
credentials = flow.credentials
service = discovery.build(
serviceName="webmasters",
version="v3",
credentials=credentials,
cache_discovery=False,
)
account = searchconsole.account.Account(service, credentials)
site_list = service.sites().list().execute()
return account, site_list
account, site_list = get_account_site_list_and_webproperty(
st.session_state.my_token_input
)
first_value = list(site_list.values())[0]
lst = []
for dicts in first_value:
a = dicts.get("siteUrl")
lst.append(a)
if lst:
container3.info("✔️ GSC credentials OK!")
with st.form(key="my_form2"):
webpropertiesNEW = st.selectbox("Select web property", lst)
col1, col2, col3 = st.columns(3)
with col1:
dimension = st.selectbox(
"Dimension",
(
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose your top dimension",
)
with col2:
nested_dimension = st.selectbox(
"Nested dimension",
(
"none",
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose a nested dimension",
)
with col3:
nested_dimension_2 = st.selectbox(
"Nested dimension 2",
(
"none",
"query",
"page",
"date",
"device",
"searchAppearance",
"country",
),
help="Choose a second nested dimension",
)
st.write("")
col1, col2 = st.columns(2)
with col1:
search_type = st.selectbox(
"Search type",
("web", "news", "video", "googleNews", "image"),
help="""
Specify the search type you want to retrieve
- **Web**: Results that appear in the All tab. This includes any image or video results shown in the All results tab.
- **Image**: Results that appear in the Images search results tab.
- **Video**: Results that appear in the Videos search results tab.
- **News**: Results that show in the News search results tab.
""",
)
with col2:
timescale = st.selectbox(
"Date range",
(
"Last 7 days",
"Last 30 days",
"Last 3 months",
"Last 6 months",
"Last 12 months",
"Last 16 months",
),
index=0,
help="Specify the date range",
)
if timescale == "Last 7 days":
timescale = -7
elif timescale == "Last 30 days":
timescale = -30
elif timescale == "Last 3 months":
timescale = -91
elif timescale == "Last 6 months":
timescale = -182
elif timescale == "Last 12 months":
timescale = -365
elif timescale == "Last 16 months":
timescale = -486
st.write("")
with st.expander("✨ Advanced Filters", expanded=False):
col1, col2, col3 = st.columns(3)
with col1:
filter_page_or_query = st.selectbox(
"Dimension to filter #1",
(
"query",
"page",
"device",
"searchAppearance",
"country",
),
help="You can choose to filter dimensions and apply filters before executing a query.",
)
with col2:
filter_type = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
help="Note that if you use Regex in your filter, you must follow `RE2` syntax.",
)
with col3:
filter_keyword = st.text_input(
"Keyword(s) to filter ",
"",
help="Add the keyword(s) you want to filter",
)
with col1:
filter_page_or_query2 = st.selectbox(
"Dimension to filter #2",
(
"query",
"page",
"device",
"searchAppearance",
"country",
),
key="filter_page_or_query2",
help="You can choose to filter dimensions and apply filters before executing a query.",
)
with col2:
filter_type2 = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
key="filter_type2",
help="Note that if you use Regex in your filter, you must follow `RE2` syntax.",
)
with col3:
filter_keyword2 = st.text_input(
"Keyword(s) to filter ",
"",
key="filter_keyword2",
help="Add the keyword(s) you want to filter",
)
with col1:
filter_page_or_query3 = st.selectbox(
"Dimension to filter #3",
(
"query",
"page",
"device",
"searchAppearance",
"country",
),
key="filter_page_or_query3",
help="You can choose to filter dimensions and apply filters before executing a query.",
)
with col2:
filter_type3 = st.selectbox(
"Filter type",
(
"contains",
"equals",
"notContains",
"notEquals",
"includingRegex",
"excludingRegex",
),
key="filter_type3",
help="Note that if you use Regex in your filter, you must follow `RE2` syntax.",
)
with col3:
filter_keyword3 = st.text_input(
"Keyword(s) to filter ",
"",
key="filter_keyword3",
help="Add the keyword(s) you want to filter",
)
st.write("")
submit_button = st.form_submit_button(
label="Fetch GSC API data", on_click=charly_form_callback
)
if (nested_dimension != "none") and (nested_dimension_2 != "none"):
if (
(dimension == nested_dimension)
or (dimension == nested_dimension_2)
or (nested_dimension == nested_dimension_2)
):
st.warning(
"🚨 Dimension and nested dimensions cannot be the same, please make sure you choose unique dimensions."
)
st.stop()
else:
pass
elif (nested_dimension != "none") and (nested_dimension_2 == "none"):
if dimension == nested_dimension:
st.warning(
"🚨 Dimension and nested dimensions cannot be the same, please make sure you choose unique dimensions."
)
st.stop()
else:
pass
else:
pass
def get_search_console_data(webproperty):
if webproperty is not None:
report = (
webproperty.query.search_type(search_type)
.range("today", days=timescale)
.dimension(dimension)
.filter(filter_page_or_query, filter_keyword, filter_type)
.filter(filter_page_or_query2, filter_keyword2, filter_type2)
.filter(filter_page_or_query3, filter_keyword3, filter_type3)
.limit(RowCap)
.get()
.to_dataframe()
)
return report
else:
st.warning("No webproperty found")
st.stop()
def get_search_console_data_nested(webproperty):
if webproperty is not None:
# query = webproperty.query.range(start="today", days=days).dimension("query")
report = (
webproperty.query.search_type(search_type)
.range("today", days=timescale)
.dimension(dimension, nested_dimension)
.filter(filter_page_or_query, filter_keyword, filter_type)
.filter(filter_page_or_query2, filter_keyword2, filter_type2)
.filter(filter_page_or_query3, filter_keyword3, filter_type3)
.limit(RowCap)
.get()
.to_dataframe()
)
return report
def get_search_console_data_nested_2(webproperty):
if webproperty is not None:
# query = webproperty.query.range(start="today", days=days).dimension("query")
report = (
webproperty.query.search_type(search_type)
.range("today", days=timescale)
.dimension(dimension, nested_dimension, nested_dimension_2)
.filter(filter_page_or_query, filter_keyword, filter_type)
.filter(filter_page_or_query2, filter_keyword2, filter_type2)
.filter(filter_page_or_query3, filter_keyword3, filter_type3)
.limit(RowCap)
.get()
.to_dataframe()
)
return report
# Here are some conditions to check which function to call
if nested_dimension == "none" and nested_dimension_2 == "none":
webproperty = account[webpropertiesNEW]
df = get_search_console_data(webproperty)
if df.empty:
st.warning(
"🚨 There's no data for your selection, please refine your search with different criteria"
)
st.stop()
elif nested_dimension_2 == "none":
webproperty = account[webpropertiesNEW]
df = get_search_console_data_nested(webproperty)
if df.empty:
st.warning(
"🚨 DataFrame is empty! Please refine your search with different criteria"
)
st.stop()
else:
webproperty = account[webpropertiesNEW]
df = get_search_console_data_nested_2(webproperty)
if df.empty:
st.warning(
"🚨 DataFrame is empty! Please refine your search with different criteria"
)
st.stop()
st.write("")
st.write(
"##### # of results returned by API call: ",
len(df.index),
)
col1, col2, col3 = st.columns([1, 1, 1])
with col1:
st.caption("")
check_box = st.checkbox(
"Ag-Grid mode", help="Tick this box to see your data in Ag-grid!"
)
st.caption("")
with col2:
st.caption("")
st.checkbox(
"Widen layout",
key="widen",
help="Tick this box to switch the layout to 'wide' mode",
)
st.caption("")
if not check_box:
@st.cache
def convert_df(df):
return df.to_csv().encode("utf-8")
csv = convert_df(df)
st.download_button(
label="Download CSV",
data=csv,
file_name="large_df.csv",
mime="text/csv",
)
st.caption("")
st.dataframe(df, height=500)
elif check_box:
df = df.reset_index()
gb = GridOptionsBuilder.from_dataframe(df)
# enables pivoting on all columns, however i'd need to change ag grid to allow export of pivoted/grouped data, however it select/filters groups
gb.configure_default_column(
enablePivot=True, enableValue=True, enableRowGroup=True
)
gb.configure_selection(selection_mode="multiple", use_checkbox=True)
gb.configure_side_bar()
gridOptions = gb.build()
st.info(
f"""
💡 Tip! Hold the '⇧ Shift' key when selecting rows to select multiple rows at once!
"""
)
response = AgGrid(
df,
gridOptions=gridOptions,
enable_enterprise_modules=True,
update_mode=GridUpdateMode.MODEL_CHANGED,
data_return_mode=DataReturnMode.FILTERED_AND_SORTED,
height=1000,
fit_columns_on_grid_load=True,
configure_side_bar=True,
)
except ValueError as ve:
st.warning("⚠️ You need to sign in to your Google account first!")
except IndexError:
st.info(
"⛔ It seems you haven’t correctly configured Google Search Console! Click [here](https://support.google.com/webmasters/answer/9008080?hl=en) for more information on how to get started!"
)
with tab2:
st.write("")
st.write("")
st.write(
"""
#### About this app
* ✔️ One-click connect to the [Google Search Console API](https://developers.google.com/webmaster-tools)
* ✔️ Easily traverse your account hierarchy
* ✔️ Go beyond the [1K row UI limit](https://www.gsqi.com/marketing-blog/how-to-bulk-export-search-features-from-gsc/)
* ✔️ Enrich your data querying with multiple dimensions layers and extra filters!
✍️ You can read the blog post [here](https://blog.streamlit.io/p/e89fd54e-e6cd-4e00-8a59-39e87536b260/) for more information.
#### Going beyond the `25K` row limit
* There's a `25K` row limit per API call on the [Cloud](https://streamlit.io/cloud) version to prevent crashes.
* You can remove that limit by forking this code and adjusting the `RowCap` variable in the `streamlit_app.py` file
#### Kudos
This app relies on Josh Carty's excellent [Search Console Python wrapper](https://github.com/joshcarty/google-searchconsole). Big kudos to him for creating it!
#### Questions, comments, or report a 🐛?
* If you have any questions or comments, please DM [me](https://twitter.com/DataChaz). Alternatively, you can ask the [Streamlit community](https://discuss.streamlit.io).
* If you find a bug, please raise an issue in [Github](https://github.com/CharlyWargnier/google-search-console-connector/pulls).
#### Known bugs
* You can filter any dimension in the table even if the dimension hasn't been pre-selected. I'm working on a fix for this.
"""
)