import os
import json
import re
import ssl
import base64
import time
import requests
from requests.adapters import HTTPAdapter
import urllib3
import PyPDF2
from pydantic import BaseModel
from playwright.sync_api import sync_playwright
from google import genai
from google.genai import types
# Optional Camoufox anti-detect browser support
try:
from camoufox.sync_api import Camoufox
HAS_CAMOUFOX = True
except ImportError:
HAS_CAMOUFOX = False
# --- FIREBASE IMPORTS ---
import firebase_admin
from firebase_admin import credentials, messaging, db
# Disable SSL warnings when bypassing KTU's misconfigured SSL certificate
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# -------------------------------------------------------------------
# CUSTOM TLS ADAPTER FOR KTU (Fixes "peer closed connection" resets)
# -------------------------------------------------------------------
class KTUTLSAdapter(HTTPAdapter):
"""Configures OpenSSL SECLEVEL=1 and legacy renegotiation so KTU's server doesn't drop connections."""
def init_poolmanager(self, *args, **kwargs):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
ctx.set_ciphers("DEFAULT:@SECLEVEL=1")
except Exception:
pass
if hasattr(ssl, "OP_LEGACY_SERVER_CONNECT"):
ctx.options |= ssl.OP_LEGACY_SERVER_CONNECT
kwargs["ssl_context"] = ctx
return super().init_poolmanager(*args, **kwargs)
def get_ktu_http_session() -> requests.Session:
session = requests.Session()
adapter = KTUTLSAdapter()
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
KTU_SESSION = get_ktu_http_session()
# -------------------------------------------------------------------
# FIREBASE SETUP
# -------------------------------------------------------------------
firebase_creds_json = os.environ.get('FIREBASE_CREDENTIALS')
if firebase_creds_json:
try:
cred_dict = json.loads(firebase_creds_json)
cred = credentials.Certificate(cred_dict)
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://kerala-timetable-db-default-rtdb.asia-southeast1.firebasedatabase.app'
})
print("✅ Firebase Admin initialized successfully.")
except Exception as e:
print(f"⚠️ Firebase Init Error: {e}")
else:
print("⚠️ FIREBASE_CREDENTIALS not found in environment variables. Push notifications will be skipped.")
def send_push_notification(title, body):
"""Fetches tokens from Firebase, broadcasts via FCM v1 send_each, and prunes dead tokens."""
if not firebase_creds_json:
print("⏭️ Skipping Push: No Firebase credentials found.")
return
try:
ref = db.reference('subscribers')
subscribers = ref.get()
if not subscribers:
print("📭 No subscribers found in database.")
return
tokens = list(subscribers.keys())
print(f"📢 Preparing to send push notification to {len(tokens)} devices...")
success_total = 0
failure_total = 0
stale_tokens = []
for i in range(0, len(tokens), 500):
batch_tokens = tokens[i:i + 500]
messages = [
messaging.Message(
notification=messaging.Notification(title=title, body=body),
token=tok
)
for tok in batch_tokens
]
response = messaging.send_each(messages)
success_total += response.success_count
failure_total += response.failure_count
for tok, send_res in zip(batch_tokens, response.responses):
if not send_res.success and send_res.exception:
err_str = str(send_res.exception).upper()
if "UNREGISTERED" in err_str or "NOT_FOUND" in err_str or "INVALID" in err_str:
stale_tokens.append(tok)
print(f"🚀 Push Sent! Success: {success_total} | Failed: {failure_total}")
if stale_tokens:
for dead_tok in stale_tokens:
ref.child(dead_tok).delete()
print(f"🧹 Cleaned up {len(stale_tokens)} expired/unregistered subscriber token(s).")
except Exception as e:
print(f"❌ Error sending push notification: {e}")
# -------------------------------------------------------------------
# AI SETUP & EXTENDED SCHEMA
# -------------------------------------------------------------------
client = genai.Client() if os.environ.get("GEMINI_API_KEY") else None
class TimetableData(BaseModel):
# Core Dashboard Config Fields
id: str
title: str
semester: str
categoryBadge: str
type: str
scheme: str
startDate: str
endDate: str
viewLink: str
pdfLink: str
# Rich S3-Template Page Fields
courseBadge: str
seoTitleTag: str
slug: str
subtitleInfo: str
startDateFormatted: str
endDateFormatted: str
faqSecondQuestion: str
faqSecondAnswer: str
# -------------------------------------------------------------------
# KTU TITLE CLEANER & SEO SLUG GENERATOR
# -------------------------------------------------------------------
def clean_ktu_raw_title(raw_title: str) -> dict:
"""Cleans messy KTU notification titles into the exact S3 standard format."""
t = raw_title.strip()
has_wp = bool(re.search(r'working\s+professionals|\(wp\)', t, flags=re.I))
# 1. Strip prefixes like "APJAKTU - ", "KTU - ", "Detailed Time Table of", "Time Table of"
t = re.sub(r'^(?:apjaktu|ktu)\s*[\-–:]+\s*', '', t, flags=re.I)
t = re.sub(r'^(?:detailed\s+)?time\s*table\s+(?:of|for)\s+', '', t, flags=re.I)
# 2. Strip suffixes like "- Notification - reg:", "Notification"
t = re.sub(r'[\s\-–:]*notification(?:\s*[\-–:]\s*reg\s*:?)?.*$', '', t, flags=re.I)
# 3. Strip Working Professionals clauses from the main title (moved to subtitle)
t = re.sub(r',?\s*including\s*\(wp\)\s*(?:\([r,\s*s]+\))?', '', t, flags=re.I)
t = re.sub(r'\s*/\s*working\s+professionals.*$', '', t, flags=re.I)
# 4. Normalize "Examinations," or "Examination" or "Exam," -> "Exam"
t = re.sub(r'\bexaminations?\b\s*,?', 'Exam', t, flags=re.I)
t = re.sub(r'\bExam\s*,', 'Exam', t, flags=re.I)
# 5. Normalize "(R,S)" spacing -> "(R, S)"
t = re.sub(r'\(\s*R\s*,\s*S\s*\)', '(R, S)', t, flags=re.I)
t = re.sub(r'\(\s*R\s*\)', '(R)', t, flags=re.I)
t = re.sub(r'\(\s*S\s*\)', '(S)', t, flags=re.I)
# 6. Extract Scheme and place "(YYYY Scheme)" cleanly at the end
scheme_match = re.search(r'\((\d{4}\s+Scheme)\)', t, flags=re.I)
scheme_str = "2024 Scheme"
if scheme_match:
scheme_str = scheme_match.group(1).title()
t_no_scheme = re.sub(r'\(\d{4}\s+Scheme\)', '', t, flags=re.I).strip()
t_no_scheme = re.sub(
r'((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{4})\s+Exam\b',
r'Exam \1',
t_no_scheme,
flags=re.I
)
if not re.search(r'\bExam\b', t_no_scheme, flags=re.I):
t_no_scheme = re.sub(
r'((?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{4})',
r'Exam \1',
t_no_scheme,
flags=re.I
)
t = f"{t_no_scheme} ({scheme_str})"
t = re.sub(r'\s+', ' ', t).strip(' ,-')
# Extract Semester (e.g., S3, S5, S7)
sem_match = re.search(r'\b(S[1-8])\b', t, flags=re.I)
semester = sem_match.group(1).upper() if sem_match else "Exam"
# Extract Course Badge (e.g., "B.Tech S3 (R, S)", "BBA Honours S5 (R)")
badge_match = re.match(r'^(.+?\bS[1-8]\s*(?:\([R,\sS]+\))?)', t, flags=re.I)
course_badge = badge_match.group(1).strip() if badge_match else f"KTU {semester}"
# Build SEO
Tag
seo_title = re.sub(
r'\bExam\b\s*(.*)$',
r'Exam Timetable Download \1',
t,
flags=re.I
).replace('(R, S)', '(R,S)')
if not seo_title.upper().startswith("KTU "):
seo_title = f"KTU {seo_title}"
# Build Subtitle
subtitle = (
"Official APJAKTU Notification • Including Working Professionals (R, S)"
if has_wp else
"Verified University Examination Schedule • Official APJAKTU Notification"
)
return {
"clean_title": t,
"semester": semester,
"course_badge": course_badge,
"scheme": scheme_str,
"seo_title": seo_title,
"subtitle": subtitle
}
def create_seo_slug(title: str) -> str:
"""Converts a clean title into the exact S3 style SEO slug."""
s = title.lower()
s = re.sub(r'^ktu\s+', '', s)
s = s.replace('b.tech', 'btech').replace('m.tech', 'mtech').replace('b.arch', 'barch').replace('b.des', 'bdes')
s = re.sub(r'\(\s*r\s*,\s*s\s*\)', 'regular-supply', s)
s = re.sub(r'\(\s*r\s*\)', 'regular', s)
s = re.sub(r'\(\s*s\s*\)', 'supply', s)
s = re.sub(r'\bexaminations?\b|\bexam\b', '', s)
s = re.sub(r'[^a-z0-9]+', '-', s)
s = re.sub(r'-+', '-', s).strip('-')
return s
def sanitize_filename(name):
"""Ensures PDF filenames don't contain invalid OS path characters."""
clean = re.sub(r'[\\/*?:"<>|]', '_', str(name))
clean = re.sub(r'\s+', '_', clean)
if not clean.lower().endswith('.pdf'):
clean += '.pdf'
return clean
def build_unique_pdf_filename(title: str, raw_att_name: str, encrypt_id: str) -> str:
"""Builds a clean, unique filename so 'Notification.pdf' attachments never collide."""
cleaned_title = clean_ktu_raw_title(title)["clean_title"]
slug_base = create_seo_slug(cleaned_title)
if not raw_att_name or raw_att_name.strip().lower() in ("notification", "notification.pdf", "timetable", "time table", "attachment"):
return sanitize_filename(f"{slug_base}.pdf")
return sanitize_filename(raw_att_name)
def is_timetable_notification(title: str) -> bool:
"""Checks whether an announcement title is an exam timetable notification."""
t = title.lower()
if any(exclude in t for exclude in ["registration", "result", "valuation", "fee", "refund", "answer script", "notified"]):
return False
if "time table" in t or "timetable" in t or "date sheet" in t:
return True
if re.search(r'\bs[1-8]\b.*\bexam(?:inations?)?\b.*\b202[4-9]\b', t):
return True
return False
# -------------------------------------------------------------------
# LIQUID GLASS HTML GENERATOR (100% EXACT S3 TIMETABLE DESIGN)
# -------------------------------------------------------------------
def generate_html_page(raw_title, pdf_filename, ai_data=None, html_output_dir="./timetable_pages"):
"""Injects the scraped & AI data into the exact S3 Liquid Glass HTML template and saves the file."""
os.makedirs(html_output_dir, exist_ok=True)
fallback_info = clean_ktu_raw_title(raw_title)
clean_title = (ai_data.get("title") if ai_data else None) or fallback_info["clean_title"]
clean_title = re.sub(r'^KTU\s+', '', clean_title, flags=re.I).strip()
slug = create_seo_slug((ai_data.get("slug") if ai_data else None) or clean_title)
semester = (ai_data.get("semester") if ai_data else None) or fallback_info["semester"]
scheme = (ai_data.get("scheme") if ai_data else None) or fallback_info["scheme"]
course_badge = (ai_data.get("courseBadge") if ai_data else None) or fallback_info["course_badge"]
seo_title_tag = (ai_data.get("seoTitleTag") if ai_data else None) or fallback_info["seo_title"]
subtitle_info = (ai_data.get("subtitleInfo") if ai_data else None) or fallback_info["subtitle"]
course_sem_label = re.sub(r'\s*\([R,\sS]+\)', '', course_badge).strip()
faq_1_q = f"When do the {course_sem_label} ({scheme}) exams start and end?"
start_fmt = ai_data.get("startDateFormatted") if ai_data else None
end_fmt = ai_data.get("endDateFormatted") if ai_data else None
if start_fmt and end_fmt and "refer" not in start_fmt.lower():
faq_1_a = (
f"The {clean_title} examinations begin on {start_fmt} "
f"and conclude on {end_fmt}. Please check the official PDF download above for your specific subject codes."
)
else:
faq_1_a = (
f"Please refer to the official {clean_title} PDF download above for the exact subject-wise start and end dates, "
f"FN/AN session timings, and slot codes for your specific branch."
)
faq_2_q = (ai_data.get("faqSecondQuestion") if ai_data else None) or "Does this timetable include Working Professionals (WP)?"
faq_2_a = (ai_data.get("faqSecondAnswer") if ai_data else None) or (
f"Please check the official APJAKTU notification header in the PDF above for {clean_title} "
f"to verify whether Working Professionals (WP) or supplementary batches are included under the {scheme}."
)
html_filename = f"{slug}.html"
html_filepath = os.path.join(html_output_dir, html_filename)
pdf_link = f"../downloads_timetable/{pdf_filename}"
html_template = """
[[SEO_TITLE_TAG]] | Kerala Timetable
Important Update: The APJ Abdul Kalam Technological University (APJAKTU) has officially published this examination timetable. Verify your subject codes, slot letters, and examination dates in the official PDF below.
15sec
Preparing Official [[SEMESTER]] Timetable PDF...
Bypassing KTU portal congestion for instant download