File size: 6,493 Bytes
ddaa017
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import requests
import re
import tempfile
import shutil
import os
from difflib import SequenceMatcher
import json
from urllib.parse import quote_plus
import zipfile
from datetime import datetime


# -----------zip_and_prepare_download--------------
def zip_and_prepare_download(file_bytes, inner_filename, zip_prefix="Download"):
    zip_filename = f"{zip_prefix}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.zip"
    zip_file_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip").name

    with zipfile.ZipFile(zip_file_path, 'w') as zipf:
        zipf.writestr(inner_filename, file_bytes)

    print(f"[DEBUG] Created ZIP at {zip_file_path} with filename {zip_filename}")
    return zip_file_path


# -----------Utilities--------------
def construct_query(row):
    query = str(row['Applicant Name'])
    optional_fields = ['Job Title', 'State', 'City', 'Skills']

    for field in optional_fields:
        if field in row and pd.notna(row[field]):
            value = row[field]
            query += f" {str(value).strip()}" if str(value).strip() else ""

    query += " linkedin"
    print(f"[DEBUG] Search Query: {query}")
    return query

def get_name_from_url(link):
    match = re.search(r'linkedin\.com/in/([a-zA-Z0-9-]+)', link)
    if match:
        profile_name = match.group(1).replace('-', ' ')
        print(f"[DEBUG] Extracted profile name from URL: {profile_name}")
        return profile_name
    return None

def calculate_similarity(name1, name2):
    similarity = SequenceMatcher(None, name1.lower().strip(), name2.lower().strip()).ratio()
    print(f"[DEBUG] Similarity between '{name1}' and '{name2}' = {similarity}")
    return similarity

def fetch_linkedin_links(query, api_key, applicant_name):
    try:
        print(f"[DEBUG] Sending request to BrightData for query: {query}")
        url = "https://api.brightdata.com/request"
        google_url = f"https://www.google.com/search?q={quote_plus(query)}"

        payload = {
            "zone": "serp_api2",
            "url": google_url,
            "method": "GET",
            "country": "us",
            "format": "raw",
            "data_format": "html"
        }

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        html = response.text

        linkedin_regex = r'https://(?:[a-z]{2,3}\.)?linkedin\.com/in/[a-zA-Z0-9\-_/]+'
        matches = re.findall(linkedin_regex, html)
        print(f"[DEBUG] Found {len(matches)} LinkedIn link(s) in search result")

        for link in matches:
            profile_name = get_name_from_url(link)
            if profile_name:
                similarity = calculate_similarity(applicant_name, profile_name)
                if similarity >= 0.5:
                    print(f"[DEBUG] Match found: {link}")
                    return link
        print(f"[DEBUG] No matching LinkedIn profile found for: {applicant_name}")
        return None

    except Exception as e:
        print(f"[ERROR] Error fetching LinkedIn link for query '{query}': {e}")
        return None


# ----------Process Excel---------------
def process_file_gradio(file_obj, api_key):
    try:
        df = pd.read_excel(file_obj.name)
        print(f"[DEBUG] Input file read successfully. Rows: {len(df)}")

        if 'Applicant Name' not in df.columns:
            return None, "❌ Missing required column: 'Applicant Name'"

        df = df[df['Applicant Name'].notna()]
        df = df[df['Applicant Name'].str.strip() != '']
        print(f"[DEBUG] Valid applicant rows after filtering: {len(df)}")

        df['Search Query'] = df.apply(construct_query, axis=1)
        df['LinkedIn Link'] = df.apply(
            lambda row: fetch_linkedin_links(row['Search Query'], api_key, row['Applicant Name']),
            axis=1
        )

        temp_dir = tempfile.mkdtemp()
        output_file = os.path.join(temp_dir, "updated_with_linkedin_links.csv")
        df.to_csv(output_file, index=False)
        print(f"[DEBUG] Output written to: {output_file}")

        with open(output_file, "rb") as f:
            csv_bytes = f.read()

        zip_path = zip_and_prepare_download(csv_bytes, "updated_with_linkedin_links.csv", "LinkedIn_Links")

        shutil.rmtree(temp_dir)
        # return zip_path, "βœ… Success! Download your file below."
        download_js = f"""
        <script>
            const link = document.createElement('a');
            link.href = '{zip_path}';
            link.download = '';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        </script>
        """
        return zip_path, download_js, "βœ… Success! File is downloading..."

    except Exception as e:
        print(f"[ERROR] Error processing file: {e}")
        return None, f"❌ Error: {str(e)}"


# ----------Gradio UI---------------
with gr.Blocks(title="LinkedIn Scraper") as demo:
    gr.Markdown("## πŸ”— LinkedIn Profile Scraper")
    gr.Markdown("Upload an Excel file with applicant details to fetch best-matching LinkedIn profile links (via Google Search using BrightData API).")

    with gr.Row():
        api_key_input = gr.Textbox(label="πŸ” BrightData API Key", type="password", placeholder="Enter your BrightData SERP API Key")
        file_input = gr.File(label="πŸ“€ Upload Excel File (.xlsx)", file_types=[".xlsx"])

    process_btn = gr.Button("πŸš€ Start Processing")
    status_output = gr.Textbox(label="πŸ“’ Status")
    # download_btn = gr.File(label="πŸ“₯ Download ZIP")
    with gr.Column():
        download_file = gr.File(label="πŸ“₯ Download ZIP", interactive=True, visible=True)
        auto_download_html = gr.HTML(visible=False)

    def run_pipeline(api_key, file):
        if not api_key:
            return None, "❗ Please enter your API key"
        if not file:
            return None, "❗ Please upload a valid Excel file"
        return process_file_gradio(file, api_key)

    # process_btn.click(
    #     fn=run_pipeline,
    #     inputs=[api_key_input, file_input],
    #     outputs=[download_btn, status_output]
    # )
    
    process_btn.click(
        fn=run_pipeline,
        inputs=[api_key_input, file_input],
        outputs=[download_file, auto_download_html, status_output]
    )

# Run app
if __name__ == "__main__":
    demo.launch()