EduForge: SheerID verification combine — API engine, doc generators, Transcript Studio (288 schools), RU/EN dashboard

This commit is contained in:
EduForge
2026-11-16 16:34:33 +02:00
commit 6f0fe138df
21 changed files with 10245 additions and 0 deletions
View File
+592
View File
@@ -0,0 +1,592 @@
"""
Enhanced Document Generator Module
Shared module for generating verification documents with anti-detection features
Features:
- Random noise injection to avoid template detection
- Color variation for uniqueness
- Dynamic layout positioning
- Multiple document types (Student ID, Transcript, Teacher Badge, Invoice)
- Font variation and randomization
Usage:
from doc_generator import generate_student_id, generate_transcript, generate_teacher_badge
# Generate student ID with noise
doc_bytes = generate_student_id("John", "Doe", "MIT")
# Generate transcript
doc_bytes = generate_transcript("John", "Doe", "2005-03-15", "MIT")
"""
import random
import time
import hashlib
from io import BytesIO
from typing import Tuple, Optional
try:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
except ImportError:
print("❌ Error: Pillow required. Install: pip install Pillow")
raise
# ============ COLOR PALETTES ============
# Multiple color schemes to avoid detection
COLOR_SCHEMES = [
# Classic blue
{"primary": (0, 51, 102), "secondary": (51, 102, 153), "accent": (255, 255, 255), "text": (51, 51, 51)},
# Dark blue
{"primary": (25, 45, 85), "secondary": (45, 85, 125), "accent": (255, 255, 255), "text": (40, 40, 40)},
# Navy
{"primary": (0, 0, 80), "secondary": (30, 30, 110), "accent": (255, 255, 255), "text": (45, 45, 45)},
# Maroon
{"primary": (128, 0, 32), "secondary": (160, 40, 72), "accent": (255, 255, 255), "text": (50, 50, 50)},
# Forest Green
{"primary": (34, 85, 51), "secondary": (51, 119, 68), "accent": (255, 255, 255), "text": (48, 48, 48)},
# Purple
{"primary": (75, 0, 130), "secondary": (100, 30, 160), "accent": (255, 255, 255), "text": (55, 55, 55)},
]
def get_random_color_scheme() -> dict:
"""Get a random color scheme"""
return random.choice(COLOR_SCHEMES)
def add_noise(img: Image.Image, intensity: float = 0.02) -> Image.Image:
"""
Add subtle noise to image to avoid template detection
Args:
img: PIL Image object
intensity: Noise intensity (0.0 - 1.0)
Returns:
Image with noise applied
"""
import numpy as np
# Convert to numpy array
arr = np.array(img, dtype=np.float32)
# Generate noise
noise = np.random.normal(0, intensity * 255, arr.shape)
# Add noise
arr = arr + noise
# Clip values
arr = np.clip(arr, 0, 255).astype(np.uint8)
return Image.fromarray(arr)
def add_simple_noise(img: Image.Image, intensity: int = 3) -> Image.Image:
"""
Add simple noise without numpy dependency
Args:
img: PIL Image object
intensity: Max pixel variation (+/-)
Returns:
Image with noise applied
"""
pixels = img.load()
width, height = img.size
# Only modify a subset of pixels for performance
for _ in range(width * height // 10):
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
try:
r, g, b = pixels[x, y][:3]
r = max(0, min(255, r + random.randint(-intensity, intensity)))
g = max(0, min(255, g + random.randint(-intensity, intensity)))
b = max(0, min(255, b + random.randint(-intensity, intensity)))
if len(pixels[x, y]) == 4:
pixels[x, y] = (r, g, b, pixels[x, y][3])
else:
pixels[x, y] = (r, g, b)
except:
pass
return img
def randomize_position(base_x: int, base_y: int, variance: int = 3) -> Tuple[int, int]:
"""Add small random offset to position"""
return (
base_x + random.randint(-variance, variance),
base_y + random.randint(-variance, variance)
)
def get_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
"""
Get font with fallback to default
Args:
size: Font size
bold: Whether to use bold font
Returns:
ImageFont object
"""
# Try different font paths
font_paths = [
"arial.ttf",
"Arial.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/System/Library/Fonts/Helvetica.ttc",
"C:\\Windows\\Fonts\\arial.ttf",
]
if bold:
font_paths = [
"arialbd.ttf",
"Arial Bold.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
"C:\\Windows\\Fonts\\arialbd.ttf",
] + font_paths
for path in font_paths:
try:
return ImageFont.truetype(path, size)
except:
continue
return ImageFont.load_default()
def generate_barcode(draw: ImageDraw.Draw, x: int, y: int, width: int = 140, height_range: Tuple[int, int] = (30, 50)):
"""Generate fake barcode pattern"""
bar_count = random.randint(20, 30)
bar_width = width // bar_count
for i in range(bar_count):
if random.random() > 0.3: # Not all bars
bar_x = x + i * bar_width
bar_height = random.randint(height_range[0], height_range[1])
bar_w = random.randint(1, max(2, bar_width - 1))
draw.rectangle([(bar_x, y), (bar_x + bar_w, y + bar_height)], fill=(0, 0, 0))
def generate_qr_placeholder(draw: ImageDraw.Draw, x: int, y: int, size: int = 60):
"""Generate fake QR code pattern"""
cell_size = size // 10
# Draw border
draw.rectangle([(x, y), (x + size, y + size)], outline=(0, 0, 0), width=2)
# Draw random pattern
for i in range(10):
for j in range(10):
if random.random() > 0.5:
cell_x = x + i * cell_size
cell_y = y + j * cell_size
draw.rectangle([(cell_x, cell_y), (cell_x + cell_size, cell_y + cell_size)], fill=(0, 0, 0))
# Draw position markers (corners)
for corner in [(x, y), (x + size - 20, y), (x, y + size - 20)]:
draw.rectangle([corner, (corner[0] + 20, corner[1] + 20)], fill=(0, 0, 0))
draw.rectangle([(corner[0] + 5, corner[1] + 5), (corner[0] + 15, corner[1] + 15)], fill=(255, 255, 255))
draw.rectangle([(corner[0] + 8, corner[1] + 8), (corner[0] + 12, corner[1] + 12)], fill=(0, 0, 0))
def generate_student_id(first: str, last: str, school: str, add_noise: bool = True) -> bytes:
"""
Generate fake student ID card with anti-detection features
Args:
first: First name
last: Last name
school: School name
add_noise: Whether to add noise for anti-detection
Returns:
PNG image bytes
"""
# Randomize dimensions slightly
w = random.randint(640, 660)
h = random.randint(390, 410)
# Random background color (slight off-white)
bg_color = (
255 - random.randint(0, 8),
255 - random.randint(0, 8),
255 - random.randint(0, 8)
)
img = Image.new("RGB", (w, h), bg_color)
draw = ImageDraw.Draw(img)
# Get random color scheme
colors = get_random_color_scheme()
# Get fonts
font_lg = get_font(random.randint(22, 26))
font_md = get_font(random.randint(16, 20))
font_sm = get_font(random.randint(12, 15))
# Header with slight position variance
header_height = random.randint(55, 65)
draw.rectangle([(0, 0), (w, header_height)], fill=colors["primary"])
title = random.choice([
"STUDENT IDENTIFICATION CARD",
"STUDENT ID CARD",
"UNIVERSITY STUDENT CARD",
"STUDENT IDENTIFICATION"
])
title_pos = randomize_position(w // 2, header_height // 2, variance=2)
draw.text(title_pos, title, fill=colors["accent"], font=font_lg, anchor="mm")
# School name
school_y = header_height + random.randint(25, 35)
school_display = school[:50] if len(school) > 50 else school
draw.text((w // 2, school_y), school_display, fill=colors["primary"], font=font_md, anchor="mm")
# Photo placeholder
photo_x = random.randint(25, 35)
photo_y = random.randint(115, 125)
photo_w = random.randint(115, 125)
photo_h = random.randint(155, 165)
draw.rectangle([(photo_x, photo_y), (photo_x + photo_w, photo_y + photo_h)],
outline=(180, 180, 180), width=2)
draw.text((photo_x + photo_w // 2, photo_y + photo_h // 2),
"PHOTO", fill=(180, 180, 180), font=font_md, anchor="mm")
# Student info
student_id = f"STU{random.randint(100000, 999999)}"
current_year = int(time.strftime('%Y'))
info_x = photo_x + photo_w + random.randint(20, 30)
info_y = random.randint(125, 135)
majors = ["Computer Science", "Business Administration", "Engineering",
"Mathematics", "Biology", "Economics", "Psychology", "Chemistry"]
info_lines = [
f"Name: {first} {last}",
f"ID: {student_id}",
f"Status: {random.choice(['Full-time Student', 'Undergraduate', 'Graduate Student'])}",
f"Major: {random.choice(majors)}",
f"Valid: {current_year}-{current_year + 1}"
]
for line in info_lines:
pos = randomize_position(info_x, info_y, variance=1)
draw.text(pos, line, fill=colors["text"], font=font_md)
info_y += random.randint(26, 32)
# Footer
footer_y = h - random.randint(38, 45)
draw.rectangle([(0, footer_y), (w, h)], fill=colors["primary"])
footer_text = random.choice([
"Property of University",
"Official Student Identification",
"This card is property of the institution"
])
draw.text((w // 2, (footer_y + h) // 2), footer_text,
fill=colors["accent"], font=font_sm, anchor="mm")
# Barcode
barcode_x = w - random.randint(160, 180)
barcode_y = photo_y + photo_h - random.randint(55, 65)
generate_barcode(draw, barcode_x, barcode_y)
# Add noise if requested
if add_noise:
img = add_simple_noise(img, intensity=random.randint(2, 4))
# Slight blur for more realistic look
if random.random() > 0.5:
img = img.filter(ImageFilter.GaussianBlur(radius=0.3))
# Save
buf = BytesIO()
# Random quality for variation
img.save(buf, format="PNG", optimize=True)
return buf.getvalue()
def generate_transcript(first: str, last: str, dob: str, school: str, add_noise: bool = True) -> bytes:
"""
Generate fake academic transcript
Args:
first: First name
last: Last name
dob: Date of birth (YYYY-MM-DD)
school: School name
add_noise: Whether to add noise
Returns:
PNG image bytes
"""
# A4-ish proportions
w = random.randint(800, 850)
h = random.randint(1100, 1150)
bg_color = (255 - random.randint(0, 5), 255 - random.randint(0, 5), 255 - random.randint(0, 5))
img = Image.new("RGB", (w, h), bg_color)
draw = ImageDraw.Draw(img)
colors = get_random_color_scheme()
font_title = get_font(random.randint(24, 28), bold=True)
font_header = get_font(random.randint(18, 22), bold=True)
font_text = get_font(random.randint(12, 14))
font_small = get_font(random.randint(10, 12))
y = 50
# School name header
draw.text((w // 2, y), school.upper(), fill=colors["primary"], font=font_title, anchor="mm")
y += 40
# Title
draw.text((w // 2, y), "OFFICIAL ACADEMIC TRANSCRIPT", fill=colors["text"], font=font_header, anchor="mm")
y += 50
# Horizontal line
draw.line([(50, y), (w - 50, y)], fill=colors["primary"], width=2)
y += 30
# Student info
student_id = f"S{random.randint(1000000, 9999999)}"
current_year = int(time.strftime('%Y'))
info = [
("Name:", f"{first} {last}"),
("Student ID:", student_id),
("Date of Birth:", dob),
("Program:", random.choice(["Bachelor of Science", "Bachelor of Arts", "Master of Science"])),
("Major:", random.choice(["Computer Science", "Business", "Engineering", "Mathematics"])),
("Academic Year:", f"{current_year - 1}-{current_year}"),
]
for label, value in info:
draw.text((60, y), label, fill=colors["text"], font=font_text)
draw.text((200, y), value, fill=colors["text"], font=font_text)
y += 25
y += 20
# Course table header
draw.rectangle([(50, y), (w - 50, y + 30)], fill=colors["primary"])
draw.text((60, y + 8), "COURSE", fill=colors["accent"], font=font_text)
draw.text((400, y + 8), "CREDITS", fill=colors["accent"], font=font_text)
draw.text((500, y + 8), "GRADE", fill=colors["accent"], font=font_text)
draw.text((600, y + 8), "POINTS", fill=colors["accent"], font=font_text)
y += 35
# Generate random courses
courses = [
"Introduction to Computer Science",
"Calculus I",
"English Composition",
"General Chemistry",
"Physics I",
"Data Structures",
"Linear Algebra",
"Statistics",
"Database Systems",
"Software Engineering",
]
random.shuffle(courses)
grades = ["A", "A-", "B+", "B", "B-", "A", "A-"]
total_credits = 0
total_points = 0
for course in courses[:random.randint(6, 8)]:
credits = random.choice([3, 4])
grade = random.choice(grades)
grade_points = {"A": 4.0, "A-": 3.7, "B+": 3.3, "B": 3.0, "B-": 2.7}[grade]
points = credits * grade_points
total_credits += credits
total_points += points
draw.text((60, y), course, fill=colors["text"], font=font_text)
draw.text((420, y), str(credits), fill=colors["text"], font=font_text)
draw.text((520, y), grade, fill=colors["text"], font=font_text)
draw.text((620, y), f"{points:.1f}", fill=colors["text"], font=font_text)
y += 22
# GPA
gpa = total_points / total_credits if total_credits > 0 else 0
y += 20
draw.line([(50, y), (w - 50, y)], fill=colors["primary"], width=1)
y += 15
draw.text((60, y), f"TOTAL CREDITS: {total_credits}", fill=colors["text"], font=font_text)
draw.text((400, y), f"GPA: {gpa:.2f}", fill=colors["primary"], font=font_header)
# Footer
y = h - 100
draw.text((60, y), "This is an official transcript issued by the Registrar's Office.",
fill=colors["text"], font=font_small)
y += 20
draw.text((60, y), f"Issue Date: {time.strftime('%B %d, %Y')}", fill=colors["text"], font=font_small)
# Add noise
if add_noise:
img = add_simple_noise(img, intensity=random.randint(2, 4))
buf = BytesIO()
img.save(buf, format="PNG", optimize=True)
return buf.getvalue()
def generate_teacher_badge(first: str, last: str, school: str, add_noise: bool = True) -> bytes:
"""
Generate fake teacher/faculty badge
Args:
first: First name
last: Last name
school: School name
add_noise: Whether to add noise
Returns:
PNG image bytes
"""
w = random.randint(490, 510)
h = random.randint(340, 360)
bg_color = (255 - random.randint(0, 8), 255 - random.randint(0, 8), 255 - random.randint(0, 8))
img = Image.new("RGB", (w, h), bg_color)
draw = ImageDraw.Draw(img)
# Use green color scheme for faculty
colors = {
"primary": (34, random.randint(100, 139), 34),
"secondary": (51, random.randint(150, 180), 68),
"accent": (255, 255, 255),
"text": (51, 51, 51)
}
font_title = get_font(random.randint(20, 24))
font_text = get_font(random.randint(14, 17))
font_small = get_font(random.randint(11, 13))
# Header
header_h = random.randint(45, 55)
draw.rectangle([(0, 0), (w, header_h)], fill=colors["primary"])
title = random.choice(["STAFF IDENTIFICATION", "FACULTY ID CARD", "EMPLOYEE BADGE"])
draw.text((w // 2, header_h // 2), title, fill=colors["accent"], font=font_title, anchor="mm")
# School name
school_y = header_h + random.randint(20, 30)
draw.text((w // 2, school_y), school[:45], fill=colors["primary"], font=font_text, anchor="mm")
# Photo placeholder
photo_x = random.randint(20, 30)
photo_y = random.randint(95, 105)
photo_w = random.randint(95, 105)
photo_h = random.randint(115, 125)
draw.rectangle([(photo_x, photo_y), (photo_x + photo_w, photo_y + photo_h)],
outline=(200, 200, 200), width=2)
draw.text((photo_x + photo_w // 2, photo_y + photo_h // 2),
"PHOTO", fill=(200, 200, 200), font=font_text, anchor="mm")
# Teacher info
teacher_id = f"T{random.randint(10000, 99999)}"
current_year = int(time.strftime('%Y'))
info_x = photo_x + photo_w + random.randint(15, 25)
info_y = photo_y
departments = ["Education", "Mathematics", "Science", "English", "History", "Computer Science"]
info_lines = [
f"Name: {first} {last}",
f"ID: {teacher_id}",
f"Position: {random.choice(['Teacher', 'Instructor', 'Faculty Member'])}",
f"Department: {random.choice(departments)}",
f"Status: Active"
]
for line in info_lines:
draw.text(randomize_position(info_x, info_y, 1), line, fill=colors["text"], font=font_text)
info_y += random.randint(20, 25)
# Valid date
draw.text((info_x, info_y + 10), f"Valid: {current_year}-{current_year + 1} School Year",
fill=(100, 100, 100), font=font_small)
# Footer
footer_y = h - random.randint(32, 40)
draw.rectangle([(0, footer_y), (w, h)], fill=colors["primary"])
draw.text((w // 2, (footer_y + h) // 2), "Property of School District",
fill=colors["accent"], font=font_small, anchor="mm")
# Add noise
if add_noise:
img = add_simple_noise(img, intensity=random.randint(2, 4))
buf = BytesIO()
img.save(buf, format="PNG", optimize=True)
return buf.getvalue()
# ============ UTILITY FUNCTIONS ============
def get_document_type_weights() -> dict:
"""
Get recommended document type weights based on success rates
Transcripts generally have higher success rates than IDs
"""
return {
"transcript": 70,
"student_id": 20,
"enrollment_letter": 10
}
def select_document_type() -> str:
"""Select document type based on weights"""
weights = get_document_type_weights()
total = sum(weights.values())
r = random.uniform(0, total)
cumulative = 0
for doc_type, weight in weights.items():
cumulative += weight
if r <= cumulative:
return doc_type
return "transcript"
if __name__ == "__main__":
print("Document Generator Test")
print("-" * 50)
# Test student ID
print("\n1. Generating Student ID...")
student_id = generate_student_id("John", "Doe", "Massachusetts Institute of Technology")
print(f" Size: {len(student_id) / 1024:.1f} KB")
# Test transcript
print("\n2. Generating Transcript...")
transcript = generate_transcript("Jane", "Smith", "2003-05-15", "Stanford University")
print(f" Size: {len(transcript) / 1024:.1f} KB")
# Test teacher badge
print("\n3. Generating Teacher Badge...")
badge = generate_teacher_badge("Robert", "Johnson", "Stuyvesant High School")
print(f" Size: {len(badge) / 1024:.1f} KB")
print("\n" + "-" * 50)
print("All documents generated successfully!")
print("\nDocument Type Weights:")
for doc_type, weight in get_document_type_weights().items():
print(f" {doc_type}: {weight}%")
+114
View File
@@ -0,0 +1,114 @@
"""Random name generator"""
import random
class NameGenerator:
"""English name generator"""
ROOTS = {
'prefixes': ['Al', 'Bri', 'Car', 'Dan', 'El', 'Fer', 'Gar', 'Har', 'Jes', 'Kar',
'Lar', 'Mar', 'Nor', 'Par', 'Quin', 'Ros', 'Sar', 'Tar', 'Val', 'Wil'],
'middles': ['an', 'en', 'in', 'on', 'ar', 'er', 'or', 'ur', 'al', 'el',
'il', 'ol', 'am', 'em', 'im', 'om', 'ay', 'ey', 'oy', 'ian'],
'suffixes': ['ton', 'son', 'man', 'ley', 'field', 'ford', 'wood', 'stone', 'worth', 'berg',
'stein', 'bach', 'heim', 'gard', 'land', 'wick', 'shire', 'dale', 'brook', 'ridge'],
'name_roots': ['Alex', 'Bern', 'Crist', 'Dav', 'Edw', 'Fred', 'Greg', 'Henr', 'Ivan', 'John',
'Ken', 'Leon', 'Mich', 'Nick', 'Oliv', 'Paul', 'Rich', 'Step', 'Thom', 'Will'],
'name_endings': ['a', 'e', 'i', 'o', 'y', 'ie', 'ey', 'an', 'en', 'in',
'on', 'er', 'ar', 'or', 'el', 'al', 'iel', 'ael', 'ine', 'lyn']
}
PATTERNS = {
'first_name': [
['prefix', 'ending'],
['name_root', 'ending'],
['prefix', 'middle', 'ending'],
['name_root', 'middle', 'ending']
],
'last_name': [
['prefix', 'suffix'],
['name_root', 'suffix'],
['prefix', 'middle', 'suffix'],
['compound']
]
}
@classmethod
def _generate_component(cls, pattern):
"""Generate name components per pattern"""
components = []
for part in pattern:
if part == 'prefix':
component = random.choice(cls.ROOTS['prefixes'])
elif part == 'middle':
component = random.choice(cls.ROOTS['middles'])
elif part == 'suffix':
component = random.choice(cls.ROOTS['suffixes'])
elif part == 'name_root':
component = random.choice(cls.ROOTS['name_roots'])
elif part == 'ending':
component = random.choice(cls.ROOTS['name_endings'])
elif part == 'compound':
part1 = random.choice(cls.ROOTS['prefixes'])
part2 = random.choice(cls.ROOTS['suffixes'])
component = part1 + part2
else:
component = ''
components.append(component)
return ''.join(components)
@classmethod
def _format_name(cls, name):
"""Format name (capitalize)"""
return name.capitalize()
@classmethod
def generate(cls):
"""
Generate random English name
Returns:
dict: contains first_name, last_name, full_name
"""
first_name_pattern = random.choice(cls.PATTERNS['first_name'])
last_name_pattern = random.choice(cls.PATTERNS['last_name'])
first_name = cls._generate_component(first_name_pattern)
last_name = cls._generate_component(last_name_pattern)
return {
'first_name': cls._format_name(first_name),
'last_name': cls._format_name(last_name),
'full_name': f"{cls._format_name(first_name)} {cls._format_name(last_name)}"
}
def generate_email(school_domain='MIT.EDU'):
"""
Generate random school email
Args:
school_domain: school domain
Returns:
str: email address
"""
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
username = ''.join(random.choice(chars) for _ in range(8))
return f"{username}@{school_domain}"
def generate_birth_date():
"""
Generate random birth date (2000-2005)
Returns:
str: YYYY-MM-DD formatted date
"""
year = 2000 + random.randint(0, 5)
month = str(random.randint(1, 12)).zfill(2)
day = str(random.randint(1, 28)).zfill(2)
return f"{year}-{month}-{day}"
+407
View File
@@ -0,0 +1,407 @@
"""PNG Student ID card generator - Penn State LionPATH"""
import random
from datetime import datetime
from io import BytesIO
import base64
def generate_psu_id():
"""Generate random PSU ID (9digits)"""
return f"9{random.randint(10000000, 99999999)}"
def generate_psu_email(first_name, last_name):
"""
Generate PSU email
format: firstName.lastName + 3-4digits @psu.edu
"""
digit_count = random.choice([3, 4])
digits = ''.join([str(random.randint(0, 9)) for _ in range(digit_count)])
email = f"{first_name.lower()}.{last_name.lower()}{digits}@psu.edu"
return email
def generate_html(first_name, last_name, school_id='2565'):
"""
Generate Penn State LionPATH HTML
Args:
first_name: First name
last_name: Last name
school_id: School ID
Returns:
str: HTML content
"""
psu_id = generate_psu_id()
name = f"{first_name} {last_name}"
date = datetime.now().strftime('%m/%d/%Y, %I:%M:%S %p')
# Random major selection
majors = [
'Computer Science (BS)',
'Software Engineering (BS)',
'Information Sciences and Technology (BS)',
'Data Science (BS)',
'Electrical Engineering (BS)',
'Mechanical Engineering (BS)',
'Business Administration (BS)',
'Psychology (BA)'
]
major = random.choice(majors)
html = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LionPATH - Student Home</title>
<style>
:root {{
--psu-blue: #1E407C; /* Penn State Nittany Navy */
--psu-light-blue: #96BEE6;
--bg-gray: #f4f4f4;
--text-color: #333;
}}
body {{
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif;
background-color: #e0e0e0; /* Browser background */
margin: 0;
padding: 20px;
color: var(--text-color);
display: flex;
justify-content: center;
}}
/* Simulated browser window */
.viewport {{
width: 100%;
max-width: 1100px;
background-color: #fff;
box-shadow: 0 5px 20px rgba(0,0,0,0.15);
min-height: 800px;
display: flex;
flex-direction: column;
}}
/* Top nav bar LionPATH */
.header {{
background-color: var(--psu-blue);
color: white;
padding: 0 20px;
height: 60px;
display: flex;
align-items: center;
justify-content: space-between;
}}
.brand {{
display: flex;
align-items: center;
gap: 15px;
}}
/* PSU Logo Simulate */
.psu-logo {{
font-family: "Georgia", serif;
font-size: 20px;
font-weight: bold;
letter-spacing: 1px;
border-right: 1px solid rgba(255,255,255,0.3);
padding-right: 15px;
}}
.system-name {{
font-size: 18px;
font-weight: 300;
}}
.user-menu {{
font-size: 14px;
display: flex;
align-items: center;
gap: 20px;
}}
.nav-bar {{
background-color: #f8f8f8;
border-bottom: 1px solid #ddd;
padding: 10px 20px;
font-size: 13px;
color: #666;
display: flex;
gap: 20px;
}}
.nav-item {{ cursor: pointer; }}
.nav-item.active {{ color: var(--psu-blue); font-weight: bold; border-bottom: 2px solid var(--psu-blue); padding-bottom: 8px; }}
/* Main content area */
.content {{
padding: 30px;
flex: 1;
}}
.page-header {{
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 20px;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}}
.page-title {{
font-size: 24px;
color: var(--psu-blue);
margin: 0;
}}
.term-selector {{
background: #fff;
border: 1px solid #ccc;
padding: 5px 10px;
border-radius: 4px;
font-size: 14px;
color: #333;
font-weight: bold;
}}
/* Student info card */
.student-card {{
background: #fcfcfc;
border: 1px solid #e0e0e0;
padding: 15px;
margin-bottom: 25px;
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
font-size: 13px;
}}
.info-label {{ color: #777; font-size: 11px; text-transform: uppercase; margin-bottom: 4px; }}
.info-val {{ font-weight: bold; color: #333; font-size: 14px; }}
.status-badge {{
background-color: #e6fffa; color: #007a5e;
padding: 4px 8px; border-radius: 4px; font-weight: bold; border: 1px solid #b2f5ea;
}}
/* Course schedule */
.schedule-table {{
width: 100%;
border-collapse: collapse;
font-size: 13px;
}}
.schedule-table th {{
text-align: left;
padding: 12px;
background-color: #f0f0f0;
border-bottom: 2px solid #ccc;
color: #555;
}}
.schedule-table td {{
padding: 15px 12px;
border-bottom: 1px solid #eee;
}}
.course-code {{ font-weight: bold; color: var(--psu-blue); }}
.course-title {{ font-weight: 500; }}
/* Print adaptation */
@media print {{
body {{ background: white; padding: 0; }}
.viewport {{ box-shadow: none; max-width: 100%; min-height: auto; }}
.nav-bar {{ display: none; }}
@page {{ margin: 1cm; size: landscape; }}
}}
</style>
</head>
<body>
<div class="viewport">
<div class="header">
<div class="brand">
<div class="psu-logo">PennState</div>
<div class="system-name">LionPATH</div>
</div>
<div class="user-menu">
<span>Welcome, <strong>{name}</strong></span>
<span>|</span>
<span>Sign Out</span>
</div>
</div>
<div class="nav-bar">
<div class="nav-item">Student Home</div>
<div class="nav-item active">My Class Schedule</div>
<div class="nav-item">Academics</div>
<div class="nav-item">Finances</div>
<div class="nav-item">Campus Life</div>
</div>
<div class="content">
<div class="page-header">
<h1 class="page-title">My Class Schedule</h1>
<div class="term-selector">
Term: <strong>Fall 2025</strong> (Aug 25 - Dec 12)
</div>
</div>
<div class="student-card">
<div>
<div class="info-label">Student Name</div>
<div class="info-val">{name}</div>
</div>
<div>
<div class="info-label">PSU ID</div>
<div class="info-val">{psu_id}</div>
</div>
<div>
<div class="info-label">Academic Program</div>
<div class="info-val">{major}</div>
</div>
<div>
<div class="info-label">Enrollment Status</div>
<div class="status-badge">✅ Enrolled</div>
</div>
</div>
<div style="margin-bottom: 10px; font-size: 12px; color: #666; text-align: right;">
Data retrieved: <span>{date}</span>
</div>
<table class="schedule-table">
<thead>
<tr>
<th width="10%">Class Nbr</th>
<th width="15%">Course</th>
<th width="35%">Title</th>
<th width="20%">Days & Times</th>
<th width="10%">Room</th>
<th width="10%">Units</th>
</tr>
</thead>
<tbody>
<tr>
<td>14920</td>
<td class="course-code">CMPSC 465</td>
<td class="course-title">Data Structures and Algorithms</td>
<td>MoWeFr 10:10AM - 11:00AM</td>
<td>Willard 062</td>
<td>3.00</td>
</tr>
<tr>
<td>18233</td>
<td class="course-code">MATH 230</td>
<td class="course-title">Calculus and Vector Analysis</td>
<td>TuTh 1:35PM - 2:50PM</td>
<td>Thomas 102</td>
<td>4.00</td>
</tr>
<tr>
<td>20491</td>
<td class="course-code">CMPSC 473</td>
<td class="course-title">Operating Systems Design</td>
<td>MoWe 2:30PM - 3:45PM</td>
<td>Westgate E201</td>
<td>3.00</td>
</tr>
<tr>
<td>11029</td>
<td class="course-code">ENGL 202C</td>
<td class="course-title">Technical Writing</td>
<td>Fr 1:25PM - 2:15PM</td>
<td>Boucke 304</td>
<td>3.00</td>
</tr>
<tr>
<td>15502</td>
<td class="course-code">STAT 318</td>
<td class="course-title">Elementary Probability</td>
<td>TuTh 9:05AM - 10:20AM</td>
<td>Osmond 112</td>
<td>3.00</td>
</tr>
</tbody>
</table>
<div style="margin-top: 50px; border-top: 1px solid #ddd; padding-top: 10px; font-size: 11px; color: #888; text-align: center;">
&copy; 2025 The Pennsylvania State University. All rights reserved.<br>
LionPATH is the student information system for Penn State.
</div>
</div>
</div>
</body>
</html>
"""
return html
def generate_image(first_name, last_name, school_id='2565'):
"""
Generate Penn State LionPATH screenshot PNG
Args:
first_name: First name
last_name: Last name
school_id: School ID
Returns:
bytes: PNG image data
"""
try:
from playwright.sync_api import sync_playwright
# Generate HTML
html_content = generate_html(first_name, last_name, school_id)
# Playwright screenshot (replaces Selenium)
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(viewport={'width': 1200, 'height': 900})
page.set_content(html_content, wait_until='load')
page.wait_for_timeout(500) # Wait for styles to load
screenshot_bytes = page.screenshot(type='png', full_page=True)
browser.close()
return screenshot_bytes
except ImportError:
raise Exception("playwright required: pip install playwright && playwright install chromium")
except Exception as e:
raise Exception(f"Image generation failed: {str(e)}")
if __name__ == '__main__':
# Test code
import sys
import io
# Fix Windows console encoding
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print("Testing PSU image generation...")
first_name = "John"
last_name = "Smith"
print(f"Name: {first_name} {last_name}")
print(f"PSU ID: {generate_psu_id()}")
print(f"Email: {generate_psu_email(first_name, last_name)}")
try:
img_data = generate_image(first_name, last_name)
# Save test image
with open('test_psu_card.png', 'wb') as f:
f.write(img_data)
print(f"✓ Image generated! Size: {len(img_data)} bytes")
print("✓ Saved as test_psu_card.png")
except Exception as e:
print(f"✗ Error: {e}")
+75
View File
@@ -0,0 +1,75 @@
"""Teacher certificate generation (PDF + PNG)"""
import random
from datetime import datetime
from io import BytesIO
from pathlib import Path
from xhtml2pdf import pisa
def _render_template(first_name: str, last_name: str) -> str:
"""Read template, replace name/employee ID/date, and expand CSS variables."""
full_name = f"{first_name} {last_name}"
employee_id = random.randint(1000000, 9999999)
current_date = datetime.now().strftime("%m/%d/%Y %I:%M %p")
template_path = Path(__file__).parent / "card-temp.html"
html = template_path.read_text(encoding="utf-8")
# Expand CSS variables for xhtml2pdf
color_map = {
"var(--primary-blue)": "#0056b3",
"var(--border-gray)": "#dee2e6",
"var(--bg-gray)": "#f8f9fa",
}
for placeholder, color in color_map.items():
html = html.replace(placeholder, color)
# Replace sample name / employee ID / date (name appears twice in template + span)
html = html.replace("Sarah J. Connor", full_name)
html = html.replace("E-9928104", f"E-{employee_id}")
html = html.replace('id="currentDate"></span>', f'id="currentDate">{current_date}</span>')
return html
def generate_teacher_pdf(first_name: str, last_name: str) -> bytes:
"""Generate teacher certificate PDF bytes."""
html = _render_template(first_name, last_name)
output = BytesIO()
pisa_status = pisa.CreatePDF(html, dest=output, encoding="utf-8")
if pisa_status.err:
raise Exception("PDF Generation failed")
pdf_data = output.getvalue()
output.close()
return pdf_data
def generate_teacher_png(first_name: str, last_name: str) -> bytes:
"""Generate PNG via Playwright screenshot (requires playwright + chromium installed)."""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc:
raise RuntimeError(
"playwright required, run `pip install playwright` then `playwright install chromium`"
) from exc
html = _render_template(first_name, last_name)
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(viewport={"width": 1200, "height": 1000})
page.set_content(html, wait_until="load")
page.wait_for_timeout(500) # let styles settle
card = page.locator(".browser-mockup")
png_bytes = card.screenshot(type="png")
browser.close()
return png_bytes
# Legacy compat: default to PDF
def generate_teacher_image(first_name: str, last_name: str) -> bytes:
return generate_teacher_pdf(first_name, last_name)