File size: 37,683 Bytes
7b55067
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfdb9d
2ddcb89
2913f49
 
 
2e56ea4
7b55067
66111ac
7b55067
09e6287
3a8e960
7b55067
9288be8
7b55067
 
4cfdb9d
 
 
 
f30d64a
7b55067
2913f49
 
 
 
f30d64a
2913f49
7b55067
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816dd30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b55067
 
 
 
 
 
b413b48
 
7b55067
7015859
7b55067
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99665c0
 
09e6287
7b55067
 
 
 
09e6287
 
 
 
 
 
 
 
 
 
 
 
7b55067
2e56ea4
4cfdb9d
 
 
 
 
 
 
 
 
 
 
 
 
 
295ba01
4cfdb9d
 
 
f30d64a
 
4cfdb9d
 
2913f49
295ba01
2913f49
 
295ba01
2913f49
4cfdb9d
 
 
 
 
 
 
24aff0c
 
 
2913f49
 
f30d64a
 
2913f49
 
f30d64a
2913f49
f30d64a
2913f49
 
 
 
 
 
 
7b55067
f1d6ab9
 
7b55067
 
2913f49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291574f
4cfdb9d
7b55067
d513d9d
24aff0c
474ca04
 
f1d6ab9
d513d9d
474ca04
 
 
 
 
 
24aff0c
 
 
 
 
 
5b41794
 
 
2e56ea4
24aff0c
5b41794
d513d9d
474ca04
2e56ea4
474ca04
13694c6
474ca04
 
2913f49
5b41794
d513d9d
474ca04
 
 
5b41794
783a4dd
 
 
474ca04
5b41794
474ca04
d513d9d
99665c0
474ca04
 
5b41794
783a4dd
d513d9d
783a4dd
5b41794
 
474ca04
d513d9d
783a4dd
474ca04
783a4dd
 
 
474ca04
783a4dd
 
474ca04
3c85ea8
4cfdb9d
2e56ea4
4cfdb9d
25bc4db
4cfdb9d
2e56ea4
25bc4db
f20b94b
5b41794
4cfdb9d
f20b94b
5b41794
 
f20b94b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfdb9d
7b55067
09e6287
a1f9248
7b55067
3a8e960
 
 
 
 
 
 
09e6287
7b55067
 
 
 
 
 
 
09e6287
7b55067
 
 
 
 
 
 
 
 
09e6287
7b55067
 
 
09e6287
7b55067
 
 
 
 
 
09e6287
7b55067
 
 
09e6287
7b55067
 
09e6287
7b55067
 
 
9f7dd1f
7b55067
 
 
 
 
 
 
 
 
9f7dd1f
7b55067
 
 
 
 
 
 
09e6287
7b55067
 
66111ac
8dc0c9a
66111ac
7b55067
 
9f7dd1f
7b55067
 
 
 
 
09e6287
7b55067
 
09e6287
7b55067
 
 
d5343ee
1f18d28
d513d9d
99665c0
 
 
1f18d28
 
7b55067
 
 
 
 
9f7dd1f
7b55067
 
 
9f7dd1f
7b55067
 
 
 
 
 
 
 
 
 
 
4068829
7b55067
 
4068829
7b55067
66111ac
9f7dd1f
66111ac
7b55067
 
09e6287
7b55067
 
 
9f7dd1f
7b55067
 
 
 
 
 
 
09e6287
7b55067
 
 
 
09e6287
7b55067
 
 
 
 
 
09e6287
7b55067
 
 
 
 
 
09e6287
fd6bb51
 
 
82b97bd
 
 
09e6287
82b97bd
 
 
 
 
 
 
 
 
 
 
09e6287
82b97bd
 
 
 
 
 
7b55067
82b97bd
09e6287
82b97bd
 
 
 
 
7b55067
ca75c69
2913f49
ca75c69
d513d9d
 
474ca04
ca75c69
 
81d479b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d513d9d
 
 
81d479b
d513d9d
81d479b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d513d9d
 
 
 
 
 
81d479b
 
 
 
2e56ea4
92f9443
89d1821
36ebc7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
faa6271
6b4ee7d
 
 
 
1307a20
 
 
 
 
 
 
 
 
 
 
 
 
e0a861f
 
 
858a793
 
e0a861f
0b016f9
e0a861f
3dc4358
 
 
9b49b5b
 
 
 
858a793
3dc4358
e0a861f
0b016f9
 
858a793
0b016f9
2f0da4f
 
858a793
 
2f0da4f
858a793
 
 
 
 
 
9b49b5b
3dc4358
 
4f7f1e3
 
 
 
42a9dff
4f7f1e3
 
42a9dff
4f7f1e3
 
42a9dff
4f7f1e3
3dc4358
 
0b016f9
3dc4358
 
 
 
 
 
 
 
 
 
 
 
 
9b49b5b
3dc4358
 
9b49b5b
3dc4358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b016f9
4f7f1e3
 
42a9dff
0b016f9
4f7f1e3
42a9dff
4f7f1e3
3dc4358
 
 
d079c96
36a7b5d
 
82b97bd
09e6287
82b97bd
 
 
 
 
 
a1f9248
82b97bd
09e6287
82b97bd
 
 
 
09e6287
82b97bd
 
 
 
 
 
 
a1f9248
3a8e960
b4a2f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
885e4ad
b4a2f4a
885e4ad
b4a2f4a
885e4ad
b4a2f4a
885e4ad
b4a2f4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a678469
82b97bd
 
 
7b55067
82b97bd
09e6287
3d7a954
8dcf13c
3d7a954
f52f788
82b97bd
 
 
 
 
ee5283f
82b97bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66111ac
2e56ea4
 
 
 
 
 
 
 
 
 
82b97bd
 
 
 
 
 
 
 
 
9ae1da2
82b97bd
 
 
fbb8761
82b97bd
 
faa6271
4cfdb9d
2e56ea4
4cfdb9d
82b97bd
 
2e56ea4
82b97bd
 
3d7a954
09e6287
24aff0c
09e6287
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
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
# Standard library imports
import datetime
import base64
import os

# Related third-party imports
import streamlit as st
from google_auth_oauthlib.flow import Flow
from googleapiclient.discovery import build
from dotenv import load_dotenv
import pandas as pd
import searchconsole
import cohere
from sklearn.metrics.pairwise import cosine_similarity
import requests
from bs4 import BeautifulSoup
from apify_client import ApifyClient
import urllib.parse
import openai
from openai import OpenAI
import re
import pycountry


load_dotenv()


# Initialize Cohere client
APIFY_API_TOKEN = os.environ.get('APIFY_API_TOKEN')
COHERE_API_KEY = os.environ["COHERE_API_KEY"]
co = cohere.Client(COHERE_API_KEY)
if not APIFY_API_TOKEN:
    st.error("APIFY_API_TOKEN is not set in the environment variables. Please set it and restart the application.")

# Initialize the ApifyClient with the API token
apify_client = ApifyClient(APIFY_API_TOKEN)

# Initialize OpenAI client
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY')
if not OPENAI_API_KEY:
    st.error("OPENAI_API_KEY is not set in the environment variables. Please set it and restart the application.")
openai_client = OpenAI(api_key=OPENAI_API_KEY)

# Configuration: Set to True if running locally, False if running on Streamlit Cloud
IS_LOCAL = False

# Constants
SEARCH_TYPES = ["web", "image", "video", "news", "discover", "googleNews"]
DATE_RANGE_OPTIONS = [
    "Last 7 Days",
    "Last 30 Days",
    "Last 3 Months",
    "Last 6 Months",
    "Last 12 Months",
    "Last 16 Months",
    "Custom Range"
]
DEVICE_OPTIONS = ["All Devices", "desktop", "mobile", "tablet"]
BASE_DIMENSIONS = ["page", "query", "country", "date"]
MAX_ROWS = 250_000
DF_PREVIEW_ROWS = 100
COUNTRY_OPTIONS = [
    ("", "All Countries"),
    ("af", "Afghanistan"), ("al", "Albania"), ("dz", "Algeria"), ("as", "American Samoa"),
    ("ad", "Andorra"), ("ao", "Angola"), ("ai", "Anguilla"), ("aq", "Antarctica"),
    ("ag", "Antigua and Barbuda"), ("ar", "Argentina"), ("am", "Armenia"), ("aw", "Aruba"),
    ("au", "Australia"), ("at", "Austria"), ("az", "Azerbaijan"), ("bs", "Bahamas"),
    ("bh", "Bahrain"), ("bd", "Bangladesh"), ("bb", "Barbados"), ("by", "Belarus"),
    ("be", "Belgium"), ("bz", "Belize"), ("bj", "Benin"), ("bm", "Bermuda"),
    ("bt", "Bhutan"), ("bo", "Bolivia"), ("ba", "Bosnia and Herzegovina"), ("bw", "Botswana"),
    ("bv", "Bouvet Island"), ("br", "Brazil"), ("io", "British Indian Ocean Territory"),
    ("bn", "Brunei"), ("bg", "Bulgaria"), ("bf", "Burkina Faso"), ("bi", "Burundi"),
    ("kh", "Cambodia"), ("cm", "Cameroon"), ("ca", "Canada"), ("cv", "Cape Verde"),
    ("ky", "Cayman Islands"), ("cf", "Central African Republic"), ("td", "Chad"),
    ("cl", "Chile"), ("cn", "China"), ("cx", "Christmas Island"), ("cc", "Cocos (Keeling) Islands"),
    ("co", "Colombia"), ("km", "Comoros"), ("cg", "Congo"), ("cd", "Congo, Democratic Republic"),
    ("ck", "Cook Islands"), ("cr", "Costa Rica"), ("ci", "Cote D'Ivoire"), ("hr", "Croatia"),
    ("cu", "Cuba"), ("cy", "Cyprus"), ("cz", "Czech Republic"), ("dk", "Denmark"),
    ("dj", "Djibouti"), ("dm", "Dominica"), ("do", "Dominican Republic"), ("ec", "Ecuador"),
    ("eg", "Egypt"), ("sv", "El Salvador"), ("gq", "Equatorial Guinea"), ("er", "Eritrea"),
    ("ee", "Estonia"), ("et", "Ethiopia"), ("fk", "Falkland Islands (Malvinas)"),
    ("fo", "Faroe Islands"), ("fj", "Fiji"), ("fi", "Finland"), ("fr", "France"),
    ("gf", "French Guiana"), ("pf", "French Polynesia"), ("tf", "French Southern Territories"),
    ("ga", "Gabon"), ("gm", "Gambia"), ("ge", "Georgia"), ("de", "Germany"), ("gh", "Ghana"),
    ("gi", "Gibraltar"), ("gr", "Greece"), ("gl", "Greenland"), ("gd", "Grenada"),
    ("gp", "Guadeloupe"), ("gu", "Guam"), ("gt", "Guatemala"), ("gn", "Guinea"),
    ("gw", "Guinea-Bissau"), ("gy", "Guyana"), ("ht", "Haiti"),
    ("hm", "Heard Island and Mcdonald Islands"), ("va", "Holy See (Vatican City State)"),
    ("hn", "Honduras"), ("hk", "Hong Kong"), ("hu", "Hungary"), ("is", "Iceland"),
    ("in", "India"), ("id", "Indonesia"), ("ir", "Iran, Islamic Republic of"), ("iq", "Iraq"),
    ("ie", "Ireland"), ("il", "Israel"),
]

# -------------
# Streamlit App Configuration
# -------------

def setup_streamlit():
    st.set_page_config(page_title="Keyword Relevance Test", layout="wide")
    st.title("Keyword Relevance Test Using Vector Embedding")
    st.divider()
    #logging.info("Streamlit app configured")

def init_session_state():
    if 'selected_property' not in st.session_state:
        st.session_state.selected_property = None
    if 'selected_search_type' not in st.session_state:
        st.session_state.selected_search_type = 'web'
    if 'selected_date_range' not in st.session_state:
        st.session_state.selected_date_range = 'Last 7 Days'
    if 'start_date' not in st.session_state:
        st.session_state.start_date = datetime.date.today() - datetime.timedelta(days=7)
    if 'end_date' not in st.session_state:
        st.session_state.end_date = datetime.date.today()
    if 'selected_dimensions' not in st.session_state:
        st.session_state.selected_dimensions = ['page', 'query']
    if 'selected_device' not in st.session_state:
        st.session_state.selected_device = 'All Devices'
    if 'custom_start_date' not in st.session_state:
        st.session_state.custom_start_date = datetime.date.today() - datetime.timedelta(days=7)
    if 'custom_end_date' not in st.session_state:
        st.session_state.custom_end_date = datetime.date.today()
    if 'relevancy_scores' not in st.session_state:
        st.session_state.relevancy_scores = {}
    #logging.info("Session state initialized")

# -------------
# Data Processing Functions
# -------------
def generate_embeddings(text_list, model_type):
    #logging.debug(f"Generating embeddings for model type: {model_type}")
    if not text_list:
        logging.warning("Text list is empty, returning empty embeddings")
        return []
    model = 'embed-english-v3.0' if model_type == 'english' else 'embed-multilingual-v3.0'
    input_type = 'search_document'
    response = co.embed(model=model, texts=text_list, input_type=input_type)
    embeddings = response.embeddings
   # logging.debug(f"Embeddings generated successfully for model type: {model_type}")
    return embeddings


def get_serp_results(query, country_code):
    if not APIFY_API_TOKEN:
        st.error("Apify API token is not set. Unable to fetch SERP results.")
        return []

    run_input = {
        "queries": query,
        "resultsPerPage": 5,
        "maxPagesPerQuery": 1,
        "languageCode": "",
        "mobileResults": False,
        "includeUnfilteredResults": False,
        "saveHtml": False,
        "saveHtmlToKeyValueStore": False,
        "includeIcons": False,
        "countryCode": country_code,
    }

    try:
        run = apify_client.actor("nFJndFXA5zjCTuudP").call(run_input=run_input)
        results = list(apify_client.dataset(run["defaultDatasetId"]).iterate_items())
        
        if results and 'organicResults' in results[0]:
            serp_data = []
            for position, item in enumerate(results[0]['organicResults'][:5], start=1):
                url = item['url']
                content = fetch_content(url, query)
                serp_data.append({'position': position, 'url': url, 'content': content})
            return serp_data
        else:
            st.warning("No organic results found in the SERP data.")
            return []
    except Exception as e:
        st.error(f"Error fetching SERP results: {str(e)}")
        return []



        
def extract_relevant_content(full_content, query):
    try:
        response = openai_client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant that extracts the most relevant content from web pages."},
                {"role": "user", "content": f"Given the following web page content and search query, extract only the most relevant parts of the content that answer or relate to the query. Limit your response to about 1000 characters. If there's no relevant content, say 'No relevant content found.'\n\nQuery: {query}\n\nContent: {full_content[:4000]}"}  # Limit input to 4000 characters
            ],
            max_tokens=500  # Adjust as needed
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        st.error(f"Error in GPT content extraction: {str(e)}")
        return "Error in content extraction"

def fetch_content(url, query):
    try:
        decoded_url = urllib.parse.unquote(url)
        response = requests.get(decoded_url, timeout=10)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Remove unwanted elements
        for unwanted in soup(['nav', 'header', 'footer', 'sidebar', 'menu', 'aside']):
            unwanted.decompose()
        
        # Try to find the main content
        main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=re.compile('content|main|body'))
        
        if main_content:
            content = main_content.get_text(separator=' ', strip=True)
        else:
            # Fallback to body if no main content is found
            content = soup.body.get_text(separator=' ', strip=True)
        
        # Clean up the content
        content = re.sub(r'\s+', ' ', content)  # Replace multiple spaces with single space
        
        # Use GPT to extract relevant content
        relevant_content = extract_relevant_content(content, query)
        return relevant_content
    except requests.RequestException:
        return ""

def calculate_relevance_score(page_content, query, co, model_type='english'):
    try:
        if not page_content.strip():
            st.warning("Page content is empty. Cannot calculate relevance score.")
            return 0
        model = 'embed-english-v3.0' if model_type == 'english' else 'embed-multilingual-v3.0'
        embeddings = co.embed(texts=[page_content, query], model=model, input_type=['search_document', 'search_query'])
        page_embedding = embeddings.embeddings[0]
        query_embedding = embeddings.embeddings[1]
        if not any(page_embedding) or not any(query_embedding):
            st.warning("One of the embeddings is empty. Returning a score of 0.")
            return 0
        score = cosine_similarity([query_embedding], [page_embedding])[0][0]
        return score
    except Exception as e:
        st.error(f"Error calculating relevance score: {str(e)}")
        return 0

def normalize_url(url):
    return url.rstrip('/').lower()

def analyze_competitors(row, co, custom_url=None, country_code=None):
    query = row['query']
    our_url = normalize_url(row['page'])
    model_type = row.get('model_type', 'english')  # Assuming you store model_type per row

    competitor_data = get_serp_results(query, country_code)

    results = []
    our_url_found = False  # Flag to check if our URL is in the results

    for data in competitor_data:
        competitor_url = normalize_url(data['url'])
        score = calculate_relevance_score(data['content'], query, co, model_type=model_type)
        is_our = competitor_url == our_url
        if is_our:
            our_url_found = True
        results.append({
            'Position': data['position'],
            'URL': competitor_url,
            'Score': score,
            'is_our_url': is_our
        })

    # Retrieve "Our Score" from the main data table
    our_score = st.session_state.relevancy_scores.get(our_url, 0)

    if not our_url_found:
        results.append({
            'Position': len(results) + 1,
            'URL': f"{our_url} (Our URL)",
            'Score': our_score,
            'is_our_url': True
        })

    # Sort results by position in ascending order
    results = sorted(results, key=lambda x: x['Position'])

    # Create DataFrame
    results_df = pd.DataFrame(results)
    results_df['Position'] = results_df['Position'].astype(int)

    # Keep only the columns we want to display
    results_df = results_df[['Position', 'URL', 'Score']]

    return results_df

def show_competitor_analysis(row, co, country_code):
    if st.button("Check Competitors", key=f"comp_{row['page']}"):
        st.write(f"Competitor Analysis for: {row['query']}")
        with st.spinner('Analyzing competitors...'):
            results_df = analyze_competitors(row, co, country_code=country_code)
            
            # Display the Markdown table
            st.markdown(results_df.to_markdown(index=False), unsafe_allow_html=True)
            
            # Extract our result for additional insights
            our_result = results_df[results_df['URL'].str.contains('\*\*')]
            
            if not our_result.empty:
                our_rank = our_result['Position'].values[0]
                total_results = len(results_df)
                our_score = our_result['Score'].values[0]
                
                st.write(f"Our page ranks **{our_rank}** out of **{total_results}** in Google search results.")
                st.write(f"Our relevancy score: **{our_score:.4f}**")
                
                if our_rank == 1:
                    st.success("Your page has the highest position in Google search results!")
                elif our_rank <= 3:
                    st.info("Your page is among the top 3 Google search results.")
                elif our_rank > total_results / 2:
                    st.warning("Your page's position is in the lower half of the Google search results. Consider optimizing your content for better visibility.")
            else:
                st.error("Our page was not found in the competitor analysis results.")

def process_gsc_data(df):
    #logging.info("Processing GSC data")
    df_sorted = df.sort_values(['impressions'], ascending=[False])
    df_unique = df_sorted.drop_duplicates(subset='page', keep='first')
    
    if 'relevancy_score' not in df_unique.columns:
        df_unique['relevancy_score'] = 0
    else:
        df_unique['relevancy_score'] = df_sorted.groupby('page')['relevancy_score'].first().values
    
    result = df_unique[['page', 'query', 'clicks', 'impressions', 'ctr', 'position', 'relevancy_score']]
    #logging.info("GSC data processed successfully")
    return result

# -------------
# Google Authentication Functions
# -------------

def load_config():
    #logging.info("Loading Google client configuration")
    client_config = {
        "web": {
            "client_id": os.environ["CLIENT_ID"],
            "client_secret": os.environ["CLIENT_SECRET"],
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
            "redirect_uris": ["https://poemsforaphrodite-gscpro.hf.space/"],
        }
    }
    #logging.info("Google client configuration loaded")
    return client_config

def init_oauth_flow(client_config):
    #logging.info("Initializing OAuth flow")
    scopes = ["https://www.googleapis.com/auth/webmasters.readonly"]
    flow = Flow.from_client_config(
        client_config,
        scopes=scopes,
        redirect_uri=client_config["web"]["redirect_uris"][0]
    )
    #logging.info("OAuth flow initialized")
    return flow

def google_auth(client_config):
   # logging.info("Starting Google authentication")
    flow = init_oauth_flow(client_config)
    auth_url, _ = flow.authorization_url(prompt="consent")
    #logging.info("Google authentication URL generated")
    return flow, auth_url

def auth_search_console(client_config, credentials):
    #logging.info("Authenticating with Google Search Console")
    token = {
        "token": credentials.token,
        "refresh_token": credentials.refresh_token,
        "token_uri": credentials.token_uri,
        "client_id": credentials.client_id,
        "client_secret": credentials.client_secret,
        "scopes": credentials.scopes,
        "id_token": getattr(credentials, "id_token", None),
    }
    #logging.info("Google Search Console authenticated")
    return searchconsole.authenticate(client_config=client_config, credentials=token)

# -------------
# Data Fetching Functions
# -------------

def list_gsc_properties(credentials):
   # logging.info("Listing GSC properties")
    service = build('webmasters', 'v3', credentials=credentials)
    site_list = service.sites().list().execute()
    properties = [site['siteUrl'] for site in site_list.get('siteEntry', [])] or ["No properties found"]
    #logging.info(f"GSC properties listed: {properties}")
    return properties

def fetch_gsc_data(webproperty, search_type, start_date, end_date, dimensions, device_type=None):
    #logging.info(f"Fetching GSC data for property: {webproperty}, search_type: {search_type}, date_range: {start_date} to {end_date}, dimensions: {dimensions}, device_type: {device_type}")
    query = webproperty.query.range(start_date, end_date).search_type(search_type).dimension(*dimensions)
    if 'device' in dimensions and device_type and device_type != 'All Devices':
        query = query.filter('device', 'equals', device_type.lower())
    try:
        df = query.limit(MAX_ROWS).get().to_dataframe()
        #logging.info("GSC data fetched successfully")
        return process_gsc_data(df)
    except Exception as e:
        #logging.error(f"Error fetching GSC data: {e}")
        show_error(e)
        return pd.DataFrame()

    
def calculate_relevancy_scores(df, model_type):
    for index, row in df.iterrows():
        if pd.isna(row['relevancy_score']) or row['relevancy_score'] == 0:
            score = calculate_single_relevancy(row)
            df.at[index, 'relevancy_score'] = score
    return df

# -------------
# Utility Functions
# -------------

def update_dimensions(selected_search_type):
   # logging.debug(f"Updating dimensions for search type: {selected_search_type}")
    return BASE_DIMENSIONS + ['device'] if selected_search_type in SEARCH_TYPES else BASE_DIMENSIONS

def calc_date_range(selection, custom_start=None, custom_end=None):
   # logging.debug(f"Calculating date range for selection: {selection}")
    range_map = {
        'Last 7 Days': 7,
        'Last 30 Days': 30,
        'Last 3 Months': 90,
        'Last 6 Months': 180,
        'Last 12 Months': 365,
        'Last 16 Months': 480
    }
    today = datetime.date.today()
    if selection == 'Custom Range':
        if custom_start and custom_end:
            #logging.debug(f"Custom date range: {custom_start} to {custom_end}")
            return custom_start, custom_end
        else:
            #logging.debug("Defaulting custom date range to last 7 days")
            return today - datetime.timedelta(days=7), today
    date_range = today - datetime.timedelta(days=range_map.get(selection, 0)), today
    #logging.debug(f"Date range calculated: {date_range}")
    return date_range

def show_error(e):
    #logging.error(f"An error occurred: {e}")
    st.error(f"An error occurred: {e}")

def property_change():
    #logging.info(f"Property changed to: {st.session_state['selected_property_selector']}")
    st.session_state.selected_property = st.session_state['selected_property_selector']

# -------------
# File & Download Operations
# -------------

def show_dataframe(report):
    #logging.info("Showing dataframe preview")
    with st.expander("Preview the First 100 Rows (Unique Pages with Top Query)"):
        st.dataframe(report.head(DF_PREVIEW_ROWS))

def download_csv_link(report):
    #logging.info("Generating CSV download link")
    def to_csv(df):
        return df.to_csv(index=False, encoding='utf-8-sig')
    csv = to_csv(report)
    b64_csv = base64.b64encode(csv.encode()).decode()
    href = f'<a href="data:file/csv;base64,{b64_csv}" download="search_console_data.csv">Download CSV File</a>'
    st.markdown(href, unsafe_allow_html=True)
    #logging.info("CSV download link generated")

# -------------
# Streamlit UI Components
# -------------

def show_google_sign_in(auth_url):
   # logging.info("Showing Google sign-in button")
    with st.sidebar:
        if st.button("Sign in with Google"):
            st.write('Please click the link below to sign in:')
            st.markdown(f'[Google Sign-In]({auth_url})', unsafe_allow_html=True)

def show_property_selector(properties, account):
  #  logging.info("Showing property selector")
    selected_property = st.selectbox(
        "Select a Search Console Property:",
        properties,
        index=properties.index(
            st.session_state.selected_property) if st.session_state.selected_property in properties else 0,
        key='selected_property_selector',
        on_change=property_change
    )
    return account[selected_property]

def show_search_type_selector():
  #  logging.info("Showing search type selector")
    return st.selectbox(
        "Select Search Type:",
        SEARCH_TYPES,
        index=SEARCH_TYPES.index(st.session_state.selected_search_type),
        key='search_type_selector'
    )

def show_model_type_selector():
  #  logging.info("Showing model type selector")
    return st.selectbox(
        "Select the embedding model:",
        ["english", "multilingual"],
        key='model_type_selector'
    )

def calculate_single_relevancy(row):
    page_content = fetch_content(row['page'], row['query'])
    query = row['query']
    model_type = st.session_state.get('model_type_selector', 'english')  # Retrieve from session state
    score = calculate_relevance_score(page_content, query, co, model_type=model_type)
    st.session_state.relevancy_scores[normalize_url(row['page'])] = score  # Ensure score is stored
    return score

def compare_with_top_result(row, co, country_code):
    query = row['query']
    our_url = row['page']
    
    # Fetch SERP results
    serp_results = get_serp_results(query, country_code)
    
    if not serp_results:
        st.error("Unable to fetch SERP results.")
        return
    
    top_result = serp_results[0]
    top_url = top_result['url']
    
    # Fetch content
    our_content = fetch_content(our_url, query)
    top_content = top_result['content']
    
    # Retrieve "Our Score" from the main data table
    our_score = st.session_state['relevancy_scores'].get(normalize_url(our_url), 0)
    
    # Calculate relevancy scores
    top_score = calculate_relevance_score(top_content, query, co, model_type=row.get('model_type', 'english'))
    
    # Prepare prompt for GPT-4
    prompt = f"""
    Compare the following two pieces of content for the query "{query}":

    1. Top-ranking page (score: {top_score:.4f}):
    {top_content[:1000]}...

    2. Our page (score: {our_score:.4f}):
    {our_content[:1000]}...

    Explain the difference in cosine similarity scores between the top-ranking page and our page. 
    What can we do to improve our score and make our content more relevant to the query?
    Provide specific, actionable recommendations.
    """

    # Call GPT-4
    try:
        response = openai_client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": "You are an SEO expert analyzing content relevance."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=1000
        )
        analysis = response.choices[0].message.content.strip()
        
        # Display results
        st.subheader("Content Comparison Analysis")
        st.write(f"**Query:** {query}")
        st.write(f"**Top-ranking URL:** {top_url}")
        st.write(f"**Our URL:** {our_url}")
        st.write(f"**Top-ranking score:** {top_score:.4f}")
        st.write(f"**Our score:** {our_score:.4f}")
        st.write("**Analysis:**")
        st.write(analysis)
    except Exception as e:
        st.error(f"Error in GPT-4 analysis: {str(e)}")

def show_tabular_data(df, co, country_code):
    st.write("Data Table with Relevancy Scores")
    
    # Pagination
    rows_per_page = 10
    total_rows = len(df)
    total_pages = (total_rows - 1) // rows_per_page + 1

    if 'current_page' not in st.session_state:
        st.session_state.current_page = 1

    # Pagination controls
    col1, col2, col3 = st.columns([1,3,1])
    with col1:
        if st.button("< Prev", disabled=st.session_state.current_page == 1):
            st.session_state.current_page -= 1
    with col2:
        st.write(f"Page {st.session_state.current_page} of {total_pages}")
    with col3:
        if st.button("Next >", disabled=st.session_state.current_page == total_pages):
            st.session_state.current_page += 1

    start_idx = (st.session_state.current_page - 1) * rows_per_page
    end_idx = start_idx + rows_per_page
    
    # Initialize or update selected_rows in session state
    if 'selected_rows' not in st.session_state or len(st.session_state.selected_rows) != len(df):
        st.session_state.selected_rows = [False] * len(df)
    
    # Add a "Calculate Relevancy" button at the top with custom styling
    st.markdown(
        """
        <style>
        .stButton > button {
            background-color: #4CAF50;
            color: white;
        }
        </style>
        """,
        unsafe_allow_html=True
    )
    if st.button("Click here to calculate relevancy for selected pages"):
        selected_indices = [i for i, selected in enumerate(st.session_state.selected_rows) if selected]
        with st.spinner('Calculating relevancy scores...'):
            for index in selected_indices:
                if pd.isna(df.iloc[index]['relevancy_score']) or df.iloc[index]['relevancy_score'] == 0:
                    df.iloc[index, df.columns.get_loc('relevancy_score')] = calculate_single_relevancy(df.iloc[index])
        st.success(f"Calculated relevancy scores for {len(selected_indices)} selected rows.")
        st.rerun()
    
    # Display column headers
    cols = st.columns([0.5, 3, 2, 1, 1, 1, 1, 1, 1])
    headers = ['Select', 'Page', 'Query', 'Clicks', 'Impressions', 'CTR', 'Position', 'Relevancy Score', 'Competitors']
    for col, header in zip(cols, headers):
        col.write(f"**{header}**")

    # Display each row
    for i, row in enumerate(df.iloc[start_idx:end_idx].itertuples(), start=start_idx):
        cols = st.columns([0.5, 3, 2, 1, 1, 1, 1, 1, 1])
        
        # Checkbox for row selection with a label
        cols[0].checkbox("Select", key=f"select_{i}", value=st.session_state.selected_rows[i],
                         on_change=lambda idx=i: setattr(st.session_state, 'selected_rows', 
                                                       [True if j == idx else x for j, x in enumerate(st.session_state.selected_rows)]))
        
        # Truncate and make the URL clickable
        truncated_url = row.page[:30] + '...' if len(row.page) > 30 else row.page
        cols[1].markdown(f"[{truncated_url}]({row.page})")
        
        cols[2].write(row.query)
        cols[3].write(row.clicks)
        cols[4].write(row.impressions)
        cols[5].write(f"{row.ctr:.2%}")
        cols[6].write(f"{row.position:.1f}")
        cols[7].write(f"{row.relevancy_score:.4f}" if not pd.isna(row.relevancy_score) and row.relevancy_score != 0 else "N/A")
        
        # Competitors column
        if not pd.isna(row.relevancy_score) and row.relevancy_score != 0:
            competitor_state_key = f"comp_state_{i}"
            competitor_button_key = f"comp_button_{i}"
            compare_state_key = f"compare_state_{i}"
            compare_button_key = f"compare_button_{i}"
            
            if competitor_state_key not in st.session_state:
                st.session_state[competitor_state_key] = False
            
            if cols[8].button("Show", key=competitor_button_key):
                st.session_state[competitor_state_key] = True
            
            if st.session_state[competitor_state_key]:
                st.write(f"Competitor Analysis for: {row.query}")
                with st.spinner('Analyzing competitors...'):
                    results_df = analyze_competitors(row, co, country_code=country_code)
                    
                    # Sort the results by Position in ascending order
                    results_df = results_df.sort_values('Position', ascending=True).reset_index(drop=True)
                    
                    # Update the Position for our URL
                    our_url_mask = results_df['URL'].str.contains('Our URL')
                    results_df.loc[our_url_mask, 'Position'] = row.position
                    
                    # Create a custom style function to highlight only our URL's row
                    def highlight_our_url(row):
                        if 'Our URL' in row['URL']:
                            return ['background-color: lightgreen'] * len(row)
                        return [''] * len(row)
                    
                    # Apply the custom style and hide the index
                    styled_df = results_df.style.apply(highlight_our_url, axis=1).hide(axis="index")
                    
                    # Display the styled DataFrame
                    st.markdown(styled_df.to_html(), unsafe_allow_html=True)
                    
                    # Extract our result for additional insights
                    our_result = results_df[results_df['URL'].str.contains('Our URL')]
                    
                    if not our_result.empty:
                        our_rank = our_result['Position'].values[0]
                        total_results = len(results_df)
                        our_score = our_result['Score'].values[0]
                        
                        st.write(f"Our page ranks {our_rank} out of {total_results} in terms of relevancy score.")
                        st.write(f"Our relevancy score: {our_score:.4f}")
                        
                        if our_rank == 1:
                            st.success("Your page has the highest relevancy score!")
                        elif our_rank <= 3:
                            st.info("Your page is among the top 3 most relevant results.")
                        elif our_rank > total_results / 2:
                            st.warning("Your page's relevancy score is in the lower half of the results. Consider optimizing your content.")
                    else:
                        st.error(f"Our page '{row.page}' is not in the results. This indicates an error in fetching or processing the page.")
    
                    if compare_state_key not in st.session_state:
                        st.session_state[compare_state_key] = False
                    
                    if cols[8].button("Compare Your Relevancy Score to the Page In First Place", key=compare_button_key):
                        st.session_state[compare_state_key] = True
                    
                    if st.session_state[compare_state_key]:
                        compare_with_top_result(row._asdict(), co, country_code)
        else:
            cols[8].write("N/A")

    return df  # Return the updated dataframe

def show_date_range_selector():
  #  logging.info("Showing date range selector")
    return st.selectbox(
        "Select Date Range:",
        DATE_RANGE_OPTIONS,
        index=DATE_RANGE_OPTIONS.index(st.session_state.selected_date_range),
        key='date_range_selector'
    )

def show_custom_date_inputs():
   # logging.info("Showing custom date inputs")
    st.session_state.custom_start_date = st.date_input("Start Date", st.session_state.custom_start_date)
    st.session_state.custom_end_date = st.date_input("End Date", st.session_state.custom_end_date)

def show_dimensions_selector(search_type):
  #  logging.info("Showing dimensions selector")
    available_dimensions = update_dimensions(search_type)
    return st.multiselect(
        "Select Dimensions:",
        available_dimensions,
        default=st.session_state.selected_dimensions,
        key='dimensions_selector'
    )

def show_paginated_dataframe(report, rows_per_page=20):
  #  logging.info("Showing paginated dataframe")
    report['position'] = report['position'].astype(int)
    report['impressions'] = pd.to_numeric(report['impressions'], errors='coerce')
    
    def format_ctr(x):
        try:
            return f"{float(x):.2%}"
        except ValueError:
            return x
    
    def format_relevancy_score(x):
        try:
            return f"{float(x):.2f}"
        except ValueError:
            return x
    
    report['ctr'] = report['ctr'].apply(format_ctr)
    report['relevancy_score'] = report['relevancy_score'].apply(format_relevancy_score)
    
    def make_clickable(url):
        return f'<a href="{url}" target="_blank">{url}</a>'
    
    report['clickable_url'] = report['page'].apply(make_clickable)
    
    columns = ['clickable_url', 'query', 'impressions', 'clicks', 'ctr', 'position', 'relevancy_score']
    report = report[columns]

    sort_column = st.selectbox("Sort by:", columns[1:], index=columns[1:].index('impressions'))
    sort_order = st.radio("Sort order:", ("Descending", "Ascending"))
    
    ascending = sort_order == "Ascending"
    
    def safe_float_convert(x):
        try:
            return float(x.rstrip('%')) / 100 if isinstance(x, str) and x.endswith('%') else float(x)
        except ValueError:
            return 0
    
    report['ctr_numeric'] = report['ctr'].apply(safe_float_convert)
    report['relevancy_score_numeric'] = report['relevancy_score'].apply(safe_float_convert)
    
    sort_column_numeric = sort_column + '_numeric' if sort_column in ['ctr', 'relevancy_score'] else sort_column
    report = report.sort_values(by=sort_column_numeric, ascending=ascending)
    
    report = report.drop(columns=['ctr_numeric', 'relevancy_score_numeric'])

    total_rows = len(report)
    total_pages = (total_rows - 1) // rows_per_page + 1

    if 'current_page' not in st.session_state:
        st.session_state.current_page = 1

    col1, col2, col3 = st.columns([1,3,1])
    with col1:
        if st.button("Previous", disabled=st.session_state.current_page == 1):
            st.session_state.current_page -= 1
    with col2:
        st.write(f"Page {st.session_state.current_page} of {total_pages}")
    with col3:
        if st.button("Next", disabled=st.session_state.current_page == total_pages):
            st.session_state.current_page += 1

    start_idx = (st.session_state.current_page - 1) * rows_per_page
    end_idx = start_idx + rows_per_page
    
    st.markdown(report.iloc[start_idx:end_idx].to_html(escape=False, index=False), unsafe_allow_html=True)

# -------------
# Main Streamlit App Function
# -------------

def main():
   # logging.info("Starting main function")
    setup_streamlit()
    print("hello")
    client_config = load_config()
    
    if 'auth_flow' not in st.session_state or 'auth_url' not in st.session_state:
        st.session_state.auth_flow, st.session_state.auth_url = google_auth(client_config)

    query_params = st.query_params
    auth_code = query_params.get("code", None)
    
    if auth_code and 'credentials' not in st.session_state:
        st.session_state.auth_flow.fetch_token(code=auth_code)
        st.session_state.credentials = st.session_state.auth_flow.credentials

    if 'credentials' not in st.session_state:
        show_google_sign_in(st.session_state.auth_url)
    else:
        init_session_state()
        account = auth_search_console(client_config, st.session_state.credentials)
        properties = list_gsc_properties(st.session_state.credentials)

        if properties:
            webproperty = show_property_selector(properties, account)
            search_type = show_search_type_selector()
            date_range_selection = show_date_range_selector()
            model_type = show_model_type_selector()
            
            # Add country selector
            selected_country = st.selectbox(
                "Select Country for SERP Results:",
                COUNTRY_OPTIONS,
                format_func=lambda x: x[1],
                key='country_selector'
            )
            country_code = selected_country[0]
            
            if date_range_selection == 'Custom Range':
                show_custom_date_inputs()
                start_date, end_date = st.session_state.custom_start_date, st.session_state.custom_end_date
            else:
                start_date, end_date = calc_date_range(date_range_selection)

            selected_dimensions = show_dimensions_selector(search_type)

            if 'report_data' not in st.session_state:
                st.session_state.report_data = None

            if st.button("Fetch Data"):
                with st.spinner('Fetching data...'):
                    st.session_state.report_data = fetch_gsc_data(webproperty, search_type, start_date, end_date, selected_dimensions)

            if st.session_state.report_data is not None and not st.session_state.report_data.empty:
                st.write("Data fetched successfully.")
                
                st.session_state.report_data = show_tabular_data(st.session_state.report_data, co, country_code)
                
                download_csv_link(st.session_state.report_data)
            elif st.session_state.report_data is not None:
                # logger.warning("No data found for the selected criteria.")
                st.warning("No data found for the selected criteria.")

if __name__ == "__main__":
   # logging.info("Running main function")
    main()
    #logger.info("Script completed")