# ============================================================================== # Shakespeare Authenticator - Standalone Gradio Dashboard # ============================================================================== import gradio as gr import torch import numpy as np from transformers import AutoModelForSequenceClassification, AutoTokenizer import time import os print("đ Starting Shakespeare Authenticator...") print(f"đĻ PyTorch version: {torch.__version__}") print(f"đ§ CUDA available: {torch.cuda.is_available()}") # Configuration MODEL_NAME = "lanretto/shakespeare-authenticator" # Your model on HF Hub TITLE = "đ Shakespeare Authenticator" DESCRIPTION = """ Distinguish authentic Shakespearean text from modern imitations using AI. This model analyzes linguistic patterns, vocabulary, and stylistic elements to determine if text was written by William Shakespeare or is a modern creation. """ # Global variables for model caching model = None tokenizer = None device = None def load_model(): """Load model and tokenizer with caching and error handling""" global model, tokenizer, device if model is not None: return model, tokenizer, device print("đ Loading model from Hugging Face Hub...") start_time = time.time() try: # Load model with explicit trust for remote code model = AutoModelForSequenceClassification.from_pretrained( MODEL_NAME, trust_remote_code=True ) tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) # Set to evaluation mode model.eval() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = model.to(device) load_time = time.time() - start_time print(f"â Model loaded successfully in {load_time:.2f}s") print(f"đ Model device: {device}") print(f"đˇī¸ Model labels: {model.config.id2label}") return model, tokenizer, device except Exception as e: print(f"â Error loading model: {e}") # Fallback to CPU if CUDA fails try: model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME) tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) model.eval() device = torch.device('cpu') model = model.to(device) print(f"â Model loaded on CPU as fallback") return model, tokenizer, device except Exception as e2: print(f"â Complete failure loading model: {e2}") raise e2 # Pre-load model at startup try: model, tokenizer, device = load_model() print("đ Model pre-loaded and ready for inference!") except Exception as e: print(f"â ī¸ Model loading failed: {e}") def classify_shakespeare(text): """ Classify whether text is authentic Shakespeare or modern imitation """ if not text.strip(): return { "error": "Please enter some text to analyze!", "prediction": None, "confidence": None, "detailed_breakdown": None } # Ensure model is loaded if model is None: try: load_model() except: return { "error": "Model failed to load. Please refresh the page.", "prediction": None, "confidence": None, "detailed_breakdown": None } try: # Tokenize the input text inputs = tokenizer( text, return_tensors="pt", truncation=True, padding=True, max_length=512 ) # Move to device inputs = {k: v.to(device) for k, v in inputs.items()} # Make prediction with torch.no_grad(): outputs = model(**inputs) logits = outputs.logits probabilities = torch.softmax(logits, dim=1) prediction = torch.argmax(logits, dim=1).item() confidence = probabilities[0][prediction].item() # Map prediction to labels (using your model's label mapping) labels = {0: "Modern Creation", 1: "Authentic Shakespeare"} result = labels[prediction] # Confidence scores confidence_pct = confidence * 100 modern_confidence = probabilities[0][0].item() * 100 shakespeare_confidence = probabilities[0][1].item() * 100 return { "error": None, "prediction": result, "confidence": f"{confidence_pct:.1f}%", "detailed_breakdown": { "Modern Creation": f"{modern_confidence:.1f}%", "Authentic Shakespeare": f"{shakespeare_confidence:.1f}%" }, "raw_scores": { "modern": modern_confidence, "shakespeare": shakespeare_confidence } } except Exception as e: return { "error": f"Prediction error: {str(e)}", "prediction": None, "confidence": None, "detailed_breakdown": None } def create_visual_output(result): """Create beautiful visual output for the prediction""" if result["error"]: return f"""
{result['error']}
Overall Confidence: {result['confidence']}
{explanation}
Paste any text above and click "Analyze Text" to see if it's authentic Shakespeare!
Paste any text above and click "Analyze Text" to see if it's authentic Shakespeare!