import os
import re
import sys
import html
import time
import json
import hashlib
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
from zoneinfo import ZoneInfo
from urllib.parse import urlparse, parse_qs, urljoin, quote_plus
from xml.sax.saxutils import escape as xml_escape
import requests
import urllib3
from bs4 import BeautifulSoup
from pydantic import BaseModel, Field
from typing import Optional, List
from google import genai
from google.genai import types
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "").strip()
PORTAL_URL = "https://chakribarta.online"
MODELS = ["gemini-3.8-flash", "gemini-3.5-flash-lite"]
JOBS_FILE = "data/jobs.json"
CA_FILE = "data/current_affairs.json"
SITEMAP_FILE = "sitemap.xml"
ROBOTS_FILE = "robots.txt"
IST = ZoneInfo("Asia/Kolkata")
# All 23 Official West Bengal District Recruitment Portals
DISTRICT_RECRUITMENT_PORTALS = {
"Alipurduar": "https://alipurduar.gov.in/notice_category/recruitment/",
"Bankura": "https://bankura.gov.in/notice_category/recruitment/",
"Birbhum": "https://birbhum.gov.in/notice_category/recruitment/",
"Cooch Behar": "https://coochbehar.gov.in/notice_category/recruitment/",
"Dakshin Dinajpur": "https://ddinajpur.nic.in/notice_category/recruitment/",
"Darjeeling": "https://darjeeling.gov.in/notice_category/recruitment/",
"Hooghly": "https://hooghly.nic.in/notice_category/recruitment/",
"Howrah": "https://howrah.gov.in/notice_category/recruitment/",
"Jalpaiguri": "https://jalpaiguri.gov.in/notice_category/recruitment/",
"Jhargram": "https://jhargram.gov.in/notice_category/recruitment/",
"Kalimpong": "https://kalimpong.gov.in/notice_category/recruitment/",
"Kolkata": "https://kolkata.gov.in/notice_category/recruitment/",
"Malda": "https://malda.gov.in/notice_category/recruitment/",
"Murshidabad": "https://murshidabad.gov.in/notice_category/recruitment/",
"Nadia": "https://nadia.gov.in/notice_category/recruitment/",
"North 24 Parganas": "https://north24parganas.gov.in/notice_category/recruitment/",
"Paschim Bardhaman": "https://paschimbardhaman.gov.in/notice_category/recruitment/",
"Paschim Medinipur": "https://paschimmedinipur.gov.in/notice_category/recruitment/",
"Purba Bardhaman": "https://purbabardhaman.nic.in/notice_category/recruitment/",
"Purba Medinipur": "https://purbamedinipur.gov.in/notice_category/recruitment/",
"Purulia": "https://purulia.gov.in/notice_category/recruitment/",
"South 24 Parganas": "https://s24pgs.gov.in/notice_category/recruitment/",
"Uttar Dinajpur": "https://uttardinajpur.gov.in/notice_category/recruitment/",
}
WB_DISTRICTS = list(DISTRICT_RECRUITMENT_PORTALS.keys())
DISTRICT_ALIASES = {
"alipurduar": "Alipurduar",
"bankura": "Bankura",
"birbhum": "Birbhum",
"suri": "Birbhum",
"bolpur": "Birbhum",
"rampurhat": "Birbhum",
"cooch behar": "Cooch Behar",
"coochbehar": "Cooch Behar",
"dinhata": "Cooch Behar",
"dakshin dinajpur": "Dakshin Dinajpur",
"balurghat": "Dakshin Dinajpur",
"darjeeling": "Darjeeling",
"siliguri": "Darjeeling",
"kurseong": "Darjeeling",
"hooghly": "Hooghly",
"hugli": "Hooghly",
"chinsurah": "Hooghly",
"howrah": "Howrah",
"haora": "Howrah",
"jalpaiguri": "Jalpaiguri",
"jhargram": "Jhargram",
"kalimpong": "Kalimpong",
"malda": "Malda",
"maldah": "Malda",
"murshidabad": "Murshidabad",
"berhampore": "Murshidabad",
"nadia": "Nadia",
"krishnanagar": "Nadia",
"kalyani": "Nadia",
"north 24 parganas": "North 24 Parganas",
"barasat": "North 24 Parganas",
"barrackpore": "North 24 Parganas",
"paschim bardhaman": "Paschim Bardhaman",
"west bardhaman": "Paschim Bardhaman",
"west burdwan": "Paschim Bardhaman",
"asansol": "Paschim Bardhaman",
"durgapur": "Paschim Bardhaman",
"paschim medinipur": "Paschim Medinipur",
"west medinipur": "Paschim Medinipur",
"west midnapore": "Paschim Medinipur",
"kharagpur": "Paschim Medinipur",
"purba bardhaman": "Purba Bardhaman",
"east bardhaman": "Purba Bardhaman",
"east burdwan": "Purba Bardhaman",
"bardhaman": "Purba Bardhaman",
"burdwan": "Purba Bardhaman",
"purba medinipur": "Purba Medinipur",
"east medinipur": "Purba Medinipur",
"east midnapore": "Purba Medinipur",
"tamluk": "Purba Medinipur",
"haldia": "Purba Medinipur",
"purulia": "Purulia",
"south 24 parganas": "South 24 Parganas",
"alipore": "South 24 Parganas",
"diamond harbour": "South 24 Parganas",
"uttar dinajpur": "Uttar Dinajpur",
"raiganj": "Uttar Dinajpur",
}
WB_STATE_FEEDS = [
"https://www.bing.com/news/search?q=West+Bengal+recruitment+WBPSC+WBP+2026&format=rss",
"https://www.bing.com/news/search?q=WBHRB+WBSSC+WBSEDCL+Kolkata+recruitment+2026&format=rss",
]
CENTRAL_GOVT_FEEDS = [
"https://www.bing.com/news/search?q=SSC+CGL+CHSL+MTS+GD+recruitment+2026+notification&format=rss",
"https://www.bing.com/news/search?q=Railway+RRB+IBPS+SBI+India+Post+GDS+recruitment+2026&format=rss",
]
WB_DISTRICT_FEEDS = [
"https://www.bing.com/news/search?q=West+Bengal+CMOH+District+Court+ICDS+recruitment+2026&format=rss",
"https://www.bing.com/news/search?q=Cooch+Behar+Jalpaiguri+Darjeeling+Alipurduar+Malda+recruitment+2026&format=rss",
"https://www.bing.com/news/search?q=Murshidabad+Nadia+North+24+Parganas+South+24+Parganas+recruitment+2026&format=rss",
"https://www.bing.com/news/search?q=Howrah+Hooghly+Bardhaman+Birbhum+Bankura+Purulia+recruitment+2026&format=rss",
"https://www.bing.com/news/search?q=Medinipur+Jhargram+Zilla+Parishad+Anganwadi+WB+recruitment+2026&format=rss",
]
CA_FEEDS = [
"https://pib.gov.in/RssMain.aspx?ModId=6&Lang=1&Regid=1",
"https://pib.gov.in/RssMain.aspx?ModId=6&Lang=1&Regid=3",
"https://www.bing.com/news/search?q=West+Bengal+government+scheme+Kolkata+news+2026&format=rss",
"https://www.bing.com/news/search?q=India+current+affairs+appointments+awards+economy+2026&format=rss",
]
class FeeItem(BaseModel):
category: str = Field(description="e.g., General/OBC, SC/ST/PwBD")
amount: str = Field(description="e.g., Rs. 160/- or Nil")
class JobPost(BaseModel):
title_en: str = Field(description="Clean English title with year 2026")
title_bn: str = Field(description="Natural Bengali translation of the job title")
organization: str
job_scope: str = Field(description="One of: wb_state, central_govt, wb_district")
district: str = Field(
default="All WB",
description="If job_scope is wb_district, exact district name from the 23 WB districts, otherwise 'All WB'"
)
category: str = Field(description="One of: latest_job, admit_card, result, answer_key")
qualification: str = Field(description="Primary tag: 10th, 12th, Graduate, or Diploma/B.Tech")
total_vacancies: Optional[int] = None
start_date: Optional[str] = Field(None, description="YYYY-MM-DD if mentioned")
last_date: Optional[str] = Field(None, description="YYYY-MM-DD if mentioned")
application_fee: List[FeeItem] = Field(default_factory=list)
age_limit: str = Field(default="As per official notification")
eligibility_en: str = Field(description="Detailed bullet-point eligibility criteria in English")
eligibility_bn: str = Field(description="Detailed bullet-point eligibility criteria in Bengali")
syllabus_en: str = Field(description="Detailed exam pattern and syllabus overview in English")
syllabus_bn: str = Field(description="Detailed exam pattern and syllabus overview in Bengali")
apply_url: str = Field(default="", description="Direct application portal or official website URL")
official_url: str = Field(default="", description="Official notification PDF or district recruitment portal URL")
seo_summary_en: str = Field(description="Original 100+ word English overview & how to apply. Set to 'SKIP' if expired 2025 or unrelated.")
seo_summary_bn: str = Field(description="Clear Bengali overview & how to apply.")
class JobBatch(BaseModel):
jobs: List[JobPost]
class CurrentAffairOneLiner(BaseModel):
topic: str = Field(description="e.g., West Bengal, National, Economy, Sports, Awards, Science")
oneliner_en: str = Field(description="Single crisp exam-ready one-liner sentence in English")
oneliner_bn: str = Field(description="Single crisp exam-ready one-liner sentence in natural Bengali")
class QuizQuestion(BaseModel):
question_en: str
question_bn: str
options_en: List[str] = Field(description="Exactly 4 options in English")
options_bn: List[str] = Field(description="Exactly 4 options in Bengali")
correct_index: int = Field(description="0, 1, 2, or 3")
explanation_en: str = Field(description="1-sentence explanation in English")
explanation_bn: str = Field(description="1-sentence explanation in Bengali")
class DailyCurrentAffairs(BaseModel):
items: List[CurrentAffairOneLiner]
quiz: List[QuizQuestion]
def compute_hash(text: str) -> str:
return hashlib.sha256(text.strip().lower().encode("utf-8")).hexdigest()
def slugify(text: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
return f"{slug[:150]}-{datetime.now(IST).strftime('%Y%m%d')}"
def load_json(path: str) -> List[dict]:
if not os.path.exists(path):
return []
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def save_json(path: str, data: List[dict]):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def clean_url(raw_url: str) -> str:
if "bing.com/news/apiclick" in raw_url:
qs = parse_qs(urlparse(raw_url).query)
if "url" in qs and qs["url"]:
return qs["url"][0]
return raw_url
def detect_wb_district(text: str) -> Optional[str]:
low = text.lower()
for alias in sorted(DISTRICT_ALIASES.keys(), key=len, reverse=True):
if re.search(rf"\b{re.escape(alias)}\b", low):
return DISTRICT_ALIASES[alias]
if re.search(r"\bkolkata\b", low):
local_markers = ["district", "cmoh", "court", "kmc", "municipal", "icds", "anganwadi", "collectorate", "bsk"]
if any(m in low for m in local_markers):
return "Kolkata"
return None
def normalize_district_metadata(entry: dict) -> dict:
combined = f"{entry.get('title_en', '')} {entry.get('organization', '')} {entry.get('district', '')}"
detected = detect_wb_district(combined)
if detected:
entry["district"] = detected
if entry.get("job_scope") != "central_govt":
entry["job_scope"] = "wb_district"
elif entry.get("job_scope") == "wb_district":
raw_dist = (entry.get("district") or "").strip()
match = next((d for d in WB_DISTRICTS if d.lower() == raw_dist.lower()), None)
entry["district"] = match if match else "Kolkata"
else:
entry["district"] = entry.get("district") or "All WB"
if entry.get("job_scope") == "wb_district" and entry.get("district") in DISTRICT_RECRUITMENT_PORTALS:
portal = DISTRICT_RECRUITMENT_PORTALS[entry["district"]]
entry["district_portal_url"] = portal
if not entry.get("official_pdf_url") or "psc.wb.gov.in" in entry.get("official_pdf_url", ""):
entry["official_pdf_url"] = portal
if not entry.get("apply_url") or "psc.wb.gov.in" in entry.get("apply_url", ""):
entry["apply_url"] = portal
return entry
def post_job_to_telegram(entry: dict):
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
return
title_bn = html.escape(entry.get("title_bn") or entry.get("title_en", ""))
title_en = html.escape(entry.get("title_en", ""))
org = html.escape(entry.get("organization", ""))
qual = html.escape(entry.get("qualification", "Check Notice"))
vac = entry.get("total_vacancies")
last_date = html.escape(entry.get("last_date") or "See Notification")
scope = entry.get("job_scope", "wb_state")
district = html.escape(entry.get("district", "All WB"))
scope_tag = "Central Govt" if scope == "central_govt" else (f"District: {district}" if scope == "wb_district" else "WB State Govt")
vac_line = f"📌 Vacancies: {vac}\n" if vac else ""
apply_link = entry.get("apply_url") or entry.get("district_portal_url") or PORTAL_URL
msg = (
f"📢 নতুন চাকরির আপডেট | Chakri Barta\n\n"
f"🇮🇳 {title_bn}\n"
f"🔹 {title_en}\n\n"
f"🏛 Organization: {org} ({scope_tag})\n"
f"🎓 Qualification: {qual}\n"
f"{vac_line}"
f"📅 Last Date: {last_date}\n\n"
f"👉 Direct Apply / District Portal | "
f"Eligibility, Syllabus & Full Details"
)
try:
api_url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
resp = requests.post(
api_url,
json={
"chat_id": TELEGRAM_CHAT_ID,
"text": msg,
"parse_mode": "HTML",
"disable_web_page_preview": False,
},
timeout=15,
)
if resp.status_code == 200:
print(f"[TELEGRAM] Posted: {entry.get('title_en')}")
else:
print(f"[TELEGRAM WARN] {resp.status_code}: {resp.text}")
time.sleep(1.5)
except Exception as e:
print(f"[TELEGRAM ERROR] {e}")
def fetch_rss_items(feed_urls: List[str], limit_per_feed: int = 6) -> List[dict]:
items = []
seen = set()
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
for url in feed_urls:
try:
res = requests.get(url, headers=headers, timeout=15, verify=False)
soup = BeautifulSoup(res.text, "html.parser")
for entry in soup.find_all("item")[:limit_per_feed]:
title_tag = entry.find("title")
title = title_tag.get_text(" ", strip=True) if title_tag else ""
if not title or title in seen or "2024" in title or "2025" in title:
continue
link = ""
link_tag = entry.find("link")
if link_tag:
link = link_tag.get_text(strip=True) or (
str(link_tag.next_sibling).strip() if link_tag.next_sibling else ""
)
desc_tag = entry.find("description")
desc = (
BeautifulSoup(desc_tag.get_text(), "html.parser").get_text(" ", strip=True)
if desc_tag
else ""
)
seen.add(title)
items.append({"title": title, "link": clean_url(link), "summary": desc[:400]})
except Exception as e:
print(f"[RSS WARN] {url}: {e}")
return items
def scrape_single_district_portal(dist_name: str, portal_url: str) -> List[dict]:
"""Fetches the top live recruitment rows & PDF URLs from one official WB district portal."""
results = []
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
try:
res = requests.get(portal_url, headers=headers, timeout=14, verify=False)
if res.status_code != 200:
print(f"[DISTRICT HTTP {res.status_code}] {dist_name}")
return results
soup = BeautifulSoup(res.text, "html.parser")
rows = soup.select("table tbody tr")
if not rows:
rows = [tr for tr in soup.select("table tr") if tr.find("td")]
for tr in rows[:4]:
cols = [c.get_text(" ", strip=True) for c in tr.find_all("td")]
if not cols:
continue
notice_title = cols[1] if (len(cols) > 1 and re.fullmatch(r"\d+\.?", cols[0])) else cols[0]
if not notice_title or len(notice_title) < 6:
continue
row_text = " ".join(cols)
if any(old_yr in row_text for old_yr in ("2022", "2023", "2024")):
continue
if "2025" in row_text and "2026" not in row_text:
continue
pdf_link = portal_url
for a_tag in tr.find_all("a", href=True):
href = a_tag["href"].strip()
if not href or href == "#" or href.startswith("javascript:"):
continue
resolved = urljoin(portal_url, href)
if ".pdf" in resolved.lower() or "/uploads/" in resolved.lower() or "/document/" in resolved.lower():
pdf_link = resolved
break
if pdf_link == portal_url:
pdf_link = resolved
extra_cols = " | ".join(c for c in cols if c != notice_title)[:220]
raw_sig = compute_hash(f"portal-{dist_name}-{notice_title[:90]}")
results.append({
"district": dist_name,
"portal_url": portal_url,
"raw_sig": raw_sig,
"title": f"[{dist_name} District] {notice_title}",
"link": pdf_link,
"summary": f"District: {dist_name} | Official Portal: {portal_url} | Details: {extra_cols}"[:450],
})
except Exception as e:
print(f"[DISTRICT PORTAL WARN] {dist_name}: {e}")
return results
def fetch_all_23_district_portals() -> List[dict]:
"""Concurrently scans ALL 23 West Bengal official district recruitment portals every 30 minutes."""
all_items = []
with ThreadPoolExecutor(max_workers=8) as executor:
futures = {
executor.submit(scrape_single_district_portal, dist_name, portal_url): dist_name
for dist_name, portal_url in DISTRICT_RECRUITMENT_PORTALS.items()
}
for future in as_completed(futures):
dist_items = future.result()
all_items.extend(dist_items)
dist_order = {name: idx for idx, name in enumerate(WB_DISTRICTS)}
all_items.sort(key=lambda x: dist_order.get(x["district"], 99))
print(f"[ALL 23 DISTRICT PORTALS] Scanned 23/23 portals -> found {len(all_items)} active notices")
return all_items
def generate_structured(prompt: str, schema):
last_err = None
for model_id in MODELS:
for attempt in range(2):
try:
response = client.models.generate_content(
model=model_id,
contents=prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema=schema,
temperature=0.2,
),
)
return schema.model_validate_json(response.text)
except Exception as e:
last_err = e
print(f"[API WARN] {model_id} (attempt {attempt + 1}) failed: {e}")
time.sleep(10)
raise last_err
def is_active_2026(job: dict) -> bool:
title = f"{job.get('title_en', '')} {job.get('title_bn', '')}"
if "2025" in title or "২০২৫" in title or "2024" in title:
return False
last_date = job.get("last_date") or ""
if last_date.startswith("2025-") or last_date.startswith("2024-"):
return False
return True
def update_daily_current_affairs() -> bool:
today_str = datetime.now(IST).strftime("%Y-%m-%d")
ca_list = load_json(CA_FILE)
if any(entry.get("date") == today_str and entry.get("items") and entry.get("quiz") for entry in ca_list):
print(f"[CA] Current affairs & quiz for {today_str} already exist.")
return True
feed_items = fetch_rss_items(CA_FEEDS, limit_per_feed=7)
print(f"[CA] Fetched {len(feed_items)} news items")
if not feed_items:
return False
news_block = "\n".join(f"- {i['title']}: {i['summary']}" for i in feed_items[:24])
prompt = (
f"You are preparing Daily Current Affairs for {today_str} for West Bengal competitive exams (WBCS, WBPSC, WBP, SSC). "
f"1) Select 8 exam-relevant news items from the verified news below (prioritizing West Bengal schemes/news, Indian govt policies, appointments, awards, economy, sports). "
f"Write each as a crisp, 1-sentence exam ONE-LINER in BOTH English (oneliner_en) and natural Bengali (oneliner_bn). "
f"2) Create a 5-question multiple-choice quiz (quiz) based directly on those 8 current affairs items, with 4 options in English and Bengali, correct_index (0-3), and a 1-line explanation in both languages. "
f"Never invent facts.\n\nVerified News:\n{news_block}"
)
try:
parsed = generate_structured(prompt, DailyCurrentAffairs)
if parsed.items:
ca_list = [d for d in ca_list if d.get("date") != today_str]
ca_list.insert(0, {
"date": today_str,
"items": [i.model_dump() for i in parsed.items],
"quiz": [q.model_dump() for q in parsed.quiz],
})
save_json(CA_FILE, ca_list[:60])
print(f"[CA] Saved {len(parsed.items)} one-liners and {len(parsed.quiz)} quiz questions for {today_str}.")
return True
return False
except Exception as e:
print(f"[CA ERROR] {type(e).__name__}: {e}")
return False
def ingest_district_notices(portal_items: List[dict], rss_items: List[dict], jobs: List[dict], existing_hashes: set) -> List[dict]:
"""Processes ALL new notices from all 23 district portals in batches so no district is dropped."""
existing_raw_sigs = {j.get("raw_sig") for j in jobs if j.get("raw_sig")}
unseen_portal_items = [it for it in portal_items if it["raw_sig"] not in existing_raw_sigs]
combined_items = unseen_portal_items + rss_items
print(f"[JOBS:wb_district] {len(unseen_portal_items)} unseen official portal notices + {len(rss_items)} RSS items")
if not combined_items:
return []
districts_str = ", ".join(WB_DISTRICTS)
new_entries = []
batch_size = 10
for start in range(0, min(len(combined_items), 40), batch_size):
chunk = combined_items[start:start + batch_size]
news_block = "\n".join(
f"- Title: {i['title']} | Details: {i['summary']} | PDF_or_Portal_URL: {i['link']}"
for i in chunk
)
prompt = (
f"You are a senior recruitment editor for Chakri Barta, a bilingual West Bengal job portal. "
f"Convert ALL valid active 2026 West Bengal district recruitment, admit card, result, or walk-in interview notices below into structured bilingual posts. "
f"STRICT RULES:\n"
f"- Process every valid notice in the list (do NOT skip valid district notices).\n"
f"- Set job_scope to 'wb_district'.\n"
f"- Set district to the exact matching district from: [{districts_str}].\n"
f"- Skip only expired 2024/2025 notices or non-recruitment notices (set seo_summary_en to 'SKIP').\n"
f"- Keep the exact PDF_or_Portal_URL provided in official_url and apply_url.\n"
f"- Extract Last Date in YYYY-MM-DD format if mentioned in Details.\n"
f"- Write detailed bullet-point eligibility_en, eligibility_bn, syllabus_en, syllabus_bn, and 100+ word seo_summary_en & seo_summary_bn.\n\n"
f"District Notices:\n{news_block}"
)
try:
parsed = generate_structured(prompt, JobBatch)
for item in parsed.jobs:
if item.seo_summary_en.strip() == "SKIP" or len(item.seo_summary_en.split()) < 25:
continue
entry = item.model_dump()
entry["job_scope"] = "wb_district"
entry = normalize_district_metadata(entry)
dedup_key = compute_hash(f"{entry['district']}-{entry['organization']}-{entry['title_en']}")
if dedup_key in existing_hashes:
continue
matched_chunk = next((c for c in chunk if c.get("district") == entry["district"]), None)
if matched_chunk and matched_chunk.get("raw_sig"):
entry["raw_sig"] = matched_chunk["raw_sig"]
entry["application_fee"] = {f.category: f.amount for f in item.application_fee}
entry["title"] = item.title_en
entry["seo_summary"] = item.seo_summary_en
entry["source_hash"] = dedup_key
entry["slug"] = slugify(f"{entry['district']}-{item.title_en}")
portal_fallback = DISTRICT_RECRUITMENT_PORTALS.get(entry["district"], "https://wb.gov.in/")
entry["official_pdf_url"] = item.official_url or portal_fallback
entry["apply_url"] = item.apply_url or item.official_url or portal_fallback
entry["district_portal_url"] = portal_fallback
entry["published_at"] = datetime.now(IST).isoformat()
if is_active_2026(entry):
jobs.insert(0, entry)
existing_hashes.add(dedup_key)
new_entries.append(entry)
except Exception as e:
print(f"[JOBS:wb_district BATCH ERROR] {type(e).__name__}: {e}")
if start + batch_size < min(len(combined_items), 40):
time.sleep(5)
return new_entries
def ingest_job_bucket(scope_name: str, feed_urls: List[str], jobs: List[dict], existing_hashes: set) -> List[dict]:
feed_items = fetch_rss_items(feed_urls, limit_per_feed=5)
print(f"[JOBS:{scope_name}] Fetched {len(feed_items)} items")
if not feed_items:
return []
news_block = "\n".join(
f"- Title: {i['title']} | Details: {i['summary']} | URL: {i['link']}" for i in feed_items[:18]
)
prompt = (
f"You are a senior recruitment editor for Chakri Barta, a bilingual West Bengal job portal. "
f"Extract up to 6 active 2026 recruitment, admit card, result, or answer key updates for scope '{scope_name}' from the items below. "
f"STRICT RULES:\n"
f"- Set job_scope to '{scope_name}' and district to 'All WB'.\n"
f"- Skip any expired 2025 or 2024 notices (set seo_summary_en to 'SKIP').\n"
f"- For eligibility_en and eligibility_bn: write detailed bullet points covering Educational Qualification, Age Limit & Category Relaxation, Domicile/Language rules, and Cut-off clarifications.\n"
f"- For syllabus_en and syllabus_bn: write detailed bullet points covering Selection Stages, Exam Pattern (Marks, Duration, Negative Marking), and Subject-wise Syllabus.\n"
f"- Keep the exact official URL provided in URL.\n"
f"- Never fabricate dates or fees not mentioned.\n\n"
f"Items:\n{news_block}"
)
new_entries = []
try:
parsed = generate_structured(prompt, JobBatch)
for item in parsed.jobs:
if item.seo_summary_en.strip() == "SKIP" or len(item.seo_summary_en.split()) < 35:
continue
dedup_key = compute_hash(f"{item.organization}-{item.title_en}")
if dedup_key in existing_hashes:
continue
entry = item.model_dump()
entry["job_scope"] = scope_name
entry["application_fee"] = {f.category: f.amount for f in item.application_fee}
entry["title"] = item.title_en
entry["seo_summary"] = item.seo_summary_en
entry["source_hash"] = dedup_key
entry["slug"] = slugify(item.title_en)
entry["official_pdf_url"] = item.official_url or item.apply_url or "https://psc.wb.gov.in/"
entry["apply_url"] = item.apply_url or item.official_url or "https://psc.wb.gov.in/"
entry["published_at"] = datetime.now(IST).isoformat()
entry = normalize_district_metadata(entry)
if is_active_2026(entry):
jobs.insert(0, entry)
existing_hashes.add(dedup_key)
new_entries.append(entry)
except Exception as e:
print(f"[JOBS:{scope_name} ERROR] {type(e).__name__}: {e}")
return new_entries
def generate_seo_files():
"""Auto-generates sitemap.xml and robots.txt for https://chakribarta.online."""
today_str = datetime.now(IST).strftime("%Y-%m-%d")
jobs = load_json(JOBS_FILE)
ca_list = load_json(CA_FILE)
urls = [
{"loc": f"{PORTAL_URL}/", "lastmod": today_str, "changefreq": "hourly", "priority": "1.0"},
{"loc": f"{PORTAL_URL}/?scope=wb_state", "lastmod": today_str, "changefreq": "hourly", "priority": "0.9"},
{"loc": f"{PORTAL_URL}/?scope=central_govt", "lastmod": today_str, "changefreq": "hourly", "priority": "0.9"},
{"loc": f"{PORTAL_URL}/?scope=wb_district", "lastmod": today_str, "changefreq": "hourly", "priority": "0.9"},
]
for dist in WB_DISTRICTS:
urls.append({
"loc": f"{PORTAL_URL}/?district={quote_plus(dist)}",
"lastmod": today_str,
"changefreq": "daily",
"priority": "0.8",
})
for day in ca_list[:30]:
d_str = (day.get("date") or today_str)[:10]
urls.append({
"loc": f"{PORTAL_URL}/?ca={quote_plus(d_str)}",
"lastmod": d_str,
"changefreq": "daily",
"priority": "0.75",
})
for j in jobs[:300]:
slug = j.get("slug") or slugify(j.get("title_en") or "wb-govt-job")
pub_raw = j.get("published_at") or today_str
lastmod = pub_raw[:10] if re.match(r"^\d{4}-\d{2}-\d{2}", pub_raw) else today_str
urls.append({
"loc": f"{PORTAL_URL}/?job={quote_plus(slug)}",
"lastmod": lastmod,
"changefreq": "daily",
"priority": "0.85",
})
xml_lines = [
'',
'',
]
for u in urls:
xml_lines.extend([
" ",
f" {xml_escape(u['loc'])}",
f" {xml_escape(u['lastmod'])}",
f" {xml_escape(u['changefreq'])}",
f" {xml_escape(u['priority'])}",
" ",
])
xml_lines.append("")
with open(SITEMAP_FILE, "w", encoding="utf-8") as f:
f.write("\n".join(xml_lines) + "\n")
robots_txt = (
"User-agent: *\n"
"Allow: /\n\n"
f"Sitemap: {PORTAL_URL}/sitemap.xml\n"
)
with open(ROBOTS_FILE, "w", encoding="utf-8") as f:
f.write(robots_txt)
print(f"[SEO] Generated {SITEMAP_FILE} ({len(urls)} URLs) and {ROBOTS_FILE}")
def update_jobs() -> bool:
jobs = [normalize_district_metadata(j) for j in load_json(JOBS_FILE) if is_active_2026(j)]
existing_hashes = {j["source_hash"] for j in jobs}
all_new_entries = []
official_district_items = fetch_all_23_district_portals()
district_rss_items = fetch_rss_items(WB_DISTRICT_FEEDS, limit_per_feed=4)
all_new_entries.extend(
ingest_district_notices(official_district_items, district_rss_items, jobs, existing_hashes)
)
for scope_name, feeds in [("wb_state", WB_STATE_FEEDS), ("central_govt", CENTRAL_GOVT_FEEDS)]:
time.sleep(6)
all_new_entries.extend(ingest_job_bucket(scope_name, feeds, jobs, existing_hashes))
save_json(JOBS_FILE, jobs[:350])
dist_count = sum(1 for j in jobs if j.get("job_scope") == "wb_district")
print(f"[JOBS] Total active 2026 jobs: {len(jobs)} (District jobs: {dist_count}, Added {len(all_new_entries)} new)")
for entry in all_new_entries[:5]:
post_job_to_telegram(entry)
return True
def main():
ca_ok = update_daily_current_affairs()
time.sleep(6)
jobs_ok = update_jobs()
generate_seo_files()
if not jobs_ok and not ca_ok:
sys.exit(1)
if __name__ == "__main__":
main()