File size: 4,831 Bytes
a60ecc7
10e43ba
 
 
e80ddde
a60ecc7
 
10e43ba
e80ddde
10e43ba
e80ddde
10e43ba
a60ecc7
10e43ba
e80ddde
10e43ba
 
 
e80ddde
10e43ba
 
 
 
e80ddde
10e43ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a60ecc7
f7f4da3
10e43ba
f7f4da3
 
a60ecc7
10e43ba
 
a60ecc7
 
10e43ba
 
 
 
 
 
 
a60ecc7
 
a92c739
10e43ba
a92c739
 
 
 
f7f4da3
 
10e43ba
 
a60ecc7
f7f4da3
a60ecc7
10e43ba
 
 
 
 
a60ecc7
10e43ba
 
 
 
a60ecc7
10e43ba
 
 
 
a60ecc7
10e43ba
a60ecc7
 
10e43ba
a60ecc7
10e43ba
 
 
 
 
a60ecc7
10e43ba
a60ecc7
10e43ba
 
 
 
a60ecc7
10e43ba
a60ecc7
 
 
 
10e43ba
 
 
 
 
 
 
 
a60ecc7
 
10e43ba
a60ecc7
10e43ba
 
a60ecc7
10e43ba
a60ecc7
10e43ba
 
a60ecc7
10e43ba
a60ecc7
10e43ba
 
 
 
a60ecc7
10e43ba
 
 
 
 
 
 
 
 
 
 
a60ecc7
 
 
 
10e43ba
 
 
 
 
 
 
 
 
 
 
 
 
 
a60ecc7
 
10e43ba
 
a60ecc7
 
 
10e43ba
f7f4da3
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
import time
import requests
import pandas as pd
import gradio as gr
import os
from urllib.parse import urlparse

# =====================================================
# CONFIGURATION (HF SAFE)
# =====================================================
HASDATA_API_KEY = os.getenv("HASDATA_API_KEY")  # ✅ From Hugging Face Secrets
HASDATA_ENDPOINT = "https://api.hasdata.com/scrape/google/serp"

TARGET_DOMAIN = "rishabhsoft.com"
COUNTRY = "us"            # "us" or "in"
LANGUAGE = "en"
LOCATION = "United States" if COUNTRY == "us" else "India"

MAX_PAGES = 10            # Top 100
RESULTS_PER_PAGE = 10
SLEEP_TIME = 1

if not HASDATA_API_KEY:
    raise ValueError("HASDATA_API_KEY is missing. Add it in Hugging Face Secrets.")

# =====================================================
# HELPERS
# =====================================================
def normalize_domain(url: str) -> str:
    try:
        return urlparse(url).netloc.replace("www.", "").lower()
    except Exception:
        return ""

# =====================================================
# CORE RANK CHECK
# =====================================================
def check_domain_rank(keyword: str) -> pd.DataFrame:
    keyword = keyword.strip()
    results = []

    headers = {
        "x-api-key": HASDATA_API_KEY
    }

    for page in range(MAX_PAGES):
        start = page * RESULTS_PER_PAGE

        params = {
            "q": keyword,
            "gl": COUNTRY,
            "hl": LANGUAGE,
            "domain": "google.com",
            "location": LOCATION,
            "start": start,
            "num": RESULTS_PER_PAGE,
            "deviceType": "desktop"
        }

        response = requests.get(
            HASDATA_ENDPOINT,
            headers=headers,
            params=params,
            timeout=30
        )

        if response.status_code != 200:
            print(f"API Error [{response.status_code}]: {response.text}")
            break

        data = response.json()

        organic_results = (
            data.get("organic_results")
            or data.get("organicResults")
            or []
        )

        for idx, item in enumerate(organic_results, start=1):
            url = item.get("link") or item.get("url") or ""
            if not url:
                continue

            domain = normalize_domain(url)

            if domain.endswith(TARGET_DOMAIN):
                results.append({
                    "Keyword": keyword,
                    "Domain": f"https://www.{TARGET_DOMAIN}/",
                    "Page": page + 1,
                    "Position on Page": idx,
                    "Absolute Rank": start + idx,
                    "URL": url,
                    "Title": item.get("title")
                })

        if results:
            break

        time.sleep(SLEEP_TIME)

    if results:
        return pd.DataFrame(results)

    return pd.DataFrame([{
        "Keyword": keyword,
        "Domain": f"https://www.{TARGET_DOMAIN}/",
        "Page": "Not Found",
        "Position on Page": "Not Found",
        "Absolute Rank": "Not Found",
        "URL": None,
        "Title": "Not ranking in top 100"
    }])

# =====================================================
# BULK EXCEL HANDLER
# =====================================================
def run_bulk_excel(file):
    if file is None:
        return None, None

    df = pd.read_excel(file)

    if "keyword" not in df.columns:
        raise ValueError("Excel must contain a 'keyword' column")

    all_results = []

    for kw in df["keyword"].dropna().unique():
        all_results.append(check_domain_rank(str(kw)))

    final_df = pd.concat(all_results, ignore_index=True)

    output_file = "hasdata_keyword_ranking.xlsx"
    final_df.to_excel(output_file, index=False)

    return final_df, output_file

# =====================================================
# GRADIO UI
# =====================================================
with gr.Blocks(title="Hasdata Google Rank Checker") as demo:
    gr.Markdown("## 🔍 Google Keyword Rank Checker (Hasdata)")
    gr.Markdown(f"**Target Domain:** https://www.{TARGET_DOMAIN}/")
    gr.Markdown(f"**Country:** {COUNTRY.upper()} | **Device:** Desktop")

    excel_input = gr.File(
        label="Upload Excel (.xlsx) with 'keyword' column",
        file_types=[".xlsx"]
    )

    run_btn = gr.Button("Check Rankings")

    output_table = gr.Dataframe(
        headers=[
            "Keyword",
            "Domain",
            "Page",
            "Position on Page",
            "Absolute Rank",
            "URL",
            "Title"
        ],
        wrap=True
    )

    download_file = gr.File(label="Download Result Excel")

    run_btn.click(
        fn=run_bulk_excel,
        inputs=excel_input,
        outputs=[output_table, download_file]
    )

demo.queue()
demo.launch()