File size: 7,979 Bytes
41ea5e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import psycopg2
import json
from datetime import datetime, timedelta



hostname = "13.201.135.196"
database = "saral_ai"
username = "saral_user"
pwd = "8k$ScgT97y9£>D"
port_id = 5432



conn = None
cur = None


def get_connection():
    return psycopg2.connect(
        host=hostname,
        dbname=database,
        user=username,
        password=pwd,
        port=port_id
    )

def check_completeness(cur, name, location, linkedin_url, headline, skills, experience):
    is_complete = True
    message = "this data is complete"

    required_fields = [name, location, linkedin_url]
    for field in required_fields:
        if field in [None, "", []]:
            is_complete = False
            message = "missing required fields"
            break

    cur.execute("SELECT id FROM saral_data WHERE linkedin_url = %s", (linkedin_url,))
    existing = cur.fetchone()
    if existing:
        return False, "this data is duplicate", False

    optional_fields = [headline, skills, experience]
    for field in optional_fields:
        if field in [None, "", []]:
            is_complete = False
            message = "some optional fields missing"
            break

    return True, message, is_complete







def data_input(json_data):
      insert_script = '''

            INSERT INTO saral_data

            (name, location, email, linkedin_url, headline, skills, about, experience, profile_pic, is_complete, created_at)

            VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)

      '''    
      with conn.cursor() as cur:
            for d in json_data:
                  name = d.get("fullName")
                  location = d.get("addressWithCountry")
                  email = d.get("email")
                  linkedin_url = d.get("linkedinUrl")
                  headline = d.get("headline")
                  profile_pic = d.get("profilePic")

                  # Safe parsing of skills
                  skills_raw = d.get("skills", [])
                  if isinstance(skills_raw, str):
                        try:
                              skills_raw = json.loads(skills_raw)
                        except:
                              skills_raw = []
                  skills_list = [s.get("title") for s in skills_raw if isinstance(s, dict)]
                  skills = json.dumps(skills_list)

                  # Safe parsing of experiences
                  experience_raw = d.get("experiences", [])
                  if isinstance(experience_raw, str):
                        try:
                              experience_raw = json.loads(experience_raw)
                        except:
                              experience_raw = []
                  experience = json.dumps(experience_raw)

                  about = d.get("about")

                  success, message, is_complete = check_completeness(
                        cur, name, location, linkedin_url, headline, skills_list, experience_raw
                  )
                  print(message)
                  
                  if not is_complete:  
                        continue 

                  created_at = datetime.now()
                  cur.execute(
                        insert_script,
                        (
                              name, location, email, linkedin_url, headline,
                              skills, about, experience, profile_pic, is_complete, created_at
                        )
                  )
                  
                  conn.commit()

            

def fetch_from_saral_data(serp_data, conn):
      if not serp_data or not isinstance(serp_data, dict):
        print("⚠️ fetch_from_saral_data: serp_data is None or not a dict")
        return [], []   # return empty lists safely
  
      results = []
      remaining = []
      one_month_ago = datetime.now() - timedelta(days=30)

      serp_json = {}
      for idx, result in enumerate(serp_data.get("organic_results", []), start=1):
            link = result.get("link")
            if link and ("linkedin.com/in/" in link or "in.linkedin.com/in/" in link):
                  clean_link = link.replace("in.linkedin.com", "linkedin.com")
                  serp_json[idx] = clean_link

      # create a fresh cursor
      with conn.cursor() as cur:
            for link in serp_json.values():
                  cur.execute("""

                        SELECT name, location, email, linkedin_url, headline, skills, about, experience, profile_pic, is_complete, created_at

                        FROM saral_data

                        WHERE linkedin_url = %s AND created_at >= %s



                  """, (link, one_month_ago))

                  row = cur.fetchone()
                  if row:
                        results.append({
                        "fullName": row[0] if row[0] else "Unknown",
                        "addressWithCountry": row[1] if row[1] else "Unknown",
                        "email": row[2] if row[2] else "-",
                        "linkedinUrl": row[3] if row[3] else "-",
                        "headline": row[4] if row[4] else "-",
                        "skills": row[5] if row[5] else [],
                        "about": row[6] if row[6] else "",
                        "experiences": row[7] if row[7] else [],
                        "profilePic": row[8] if row[8] else None,   
                        "is_complete": row[9],
                        "created_at": row[10]
                        })


                  else:
                        remaining.append(link)

      return results, remaining


def store_prompt(conn, prompt: str, parsed_json: dict):
    job_title = parsed_json.get("job_title")
    skills = parsed_json.get("skills", [])
    experience = parsed_json.get("experience")
    location = parsed_json.get("location", [])
    work_preference = parsed_json.get("work_preference")
    job_type = parsed_json.get("job_type")
    is_indian = parsed_json.get("is_indian")

    try:
        with conn.cursor() as cur:
            cur.execute("""

                INSERT INTO saral_prompts

                (prompt, job_title, skills, experience, location, work_preference, job_type, created_at,is_indian)

                VALUES (%s, %s, %s, %s, %s, %s, %s, %s,%s)

            """, (
                prompt,
                job_title,
                json.dumps(skills) if skills else None,   # ensure proper type
                experience,
                location if location else None,
                work_preference,
                job_type,
                datetime.now(),
                is_indian
            ))
        conn.commit()
    except Exception as e:
        print("Error inserting prompt:", e)
        conn.rollback()   




try:
      conn = psycopg2.connect(
            host=hostname, dbname=database, user=username, password=pwd, port=port_id
      )

      cur = conn.cursor()

      create_script = """

                  CREATE TABLE IF NOT EXISTS saral_data (

                  id SERIAL PRIMARY KEY,

                  name TEXT,

                  location TEXT,

                  email TEXT,

                  linkedin_url TEXT,

                  headline TEXT,

                  skills JSONB,

                  about TEXT,

                  experience JSONB,

                  profile_pic TEXT,          

                  is_complete BOOLEAN,

                  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

                  );

            """
      
      # cur.execute(create_script)
            
      
      

      conn.commit()
      
      
      
      
except Exception as error:
    print(error)


finally:
#     if cur is not None:
#         cur.close()
#     if conn is not None:
#         conn.close()
      pass