goodreads / demo.py
fguryel's picture
Deploy ML project
ce92e54
"""
Demo script for Book Popularity Predictor
==========================================
This script demonstrates the machine learning model capabilities
without the web interface. Perfect for showcasing the core functionality.
"""
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))
from src.prediction_utils import BookPopularityPredictor
import pandas as pd
def run_demo():
"""Run demonstration of the book popularity prediction model"""
print("๐Ÿ“š Book Popularity Predictor - Demo")
print("=" * 50)
# Initialize predictor
predictor = BookPopularityPredictor(models_dir='models')
# Load model
if not predictor.load_model_components():
print("โŒ Failed to load model. Please ensure the model is trained.")
print("Run: python src/model_training.py")
return
print("โœ… Model loaded successfully!")
print(f"๐Ÿ“Š Available authors: {len(predictor.get_top_authors())}")
# Demo predictions
demo_cases = [
{
"author": "Stephen King",
"ratings_count": 100000,
"reviews_count": 12000,
"description": "Popular Stephen King horror novel"
},
{
"author": "J.K. Rowling",
"ratings_count": 500000,
"reviews_count": 60000,
"description": "New Harry Potter series book"
},
{
"author": "Jane Austen",
"ratings_count": 75000,
"reviews_count": 9000,
"description": "Classic romance novel reprint"
},
{
"author": "Rick Riordan",
"ratings_count": 200000,
"reviews_count": 25000,
"description": "New Percy Jackson adventure"
}
]
print("\\n๐ŸŽฏ Demo Predictions:")
print("-" * 50)
for i, case in enumerate(demo_cases, 1):
print(f"\\n{i}. {case['description']}")
print(f" Author: {case['author']}")
print(f" Expected Ratings: {case['ratings_count']:,}")
print(f" Expected Reviews: {case['reviews_count']:,}")
# Make prediction
result = predictor.predict_book_rating(
case['author'],
case['ratings_count'],
case['reviews_count']
)
if "error" in result:
print(f" โŒ Error: {result['error']}")
else:
predicted_rating = result["predicted_rating"]
confidence = result["confidence"]
# Rating interpretation
if predicted_rating >= 4.5:
rating_desc = "Excellent (โญโญโญโญโญ)"
elif predicted_rating >= 4.0:
rating_desc = "Very Good (โญโญโญโญ)"
elif predicted_rating >= 3.5:
rating_desc = "Good (โญโญโญ)"
else:
rating_desc = "Average (โญโญ)"
print(f" ๐ŸŽฏ Predicted Rating: {predicted_rating}/5.0 - {rating_desc}")
print(f" ๐Ÿ“Š Confidence: {confidence}")
# Model insights
print("\\n" + "=" * 50)
print("๐Ÿง  Model Insights:")
print("-" * 50)
print("๐Ÿ” Most Important Features:")
print(" 1. Author Identity (33.7% importance)")
print(" 2. Author Book Count (13.9% importance)")
print(" 3. Reviews Count (11.8% importance)")
print(" 4. Ratings Count (11.0% importance)")
print("\\n๐Ÿ“ˆ Model Performance:")
print(" โ€ข Test Rยฒ Score: 0.544 (Medium accuracy)")
print(" โ€ข Mean Absolute Error: ยฑ0.121 rating points")
print(" โ€ข Training Data: 990+ books from Goodreads")
print("\\n๐ŸŽฏ Prediction Guidelines:")
print(" โ€ข Higher ratings count โ†’ More reliable prediction")
print(" โ€ข Popular authors โ†’ Higher confidence")
print(" โ€ข Typical rating range: 3.0 - 4.8")
print(" โ€ข Average book rating: 4.1")
# Interactive mode
print("\\n" + "=" * 50)
print("๐ŸŽฎ Try Your Own Prediction!")
print("-" * 50)
try:
# Show available authors
authors = predictor.get_top_authors()
print("\\n๐Ÿ“š Available Authors (Top 20):")
for i, author in enumerate(authors[:10], 1):
print(f" {i:2d}. {author}")
print(" ... and 10 more authors")
# Get user input
print("\\nEnter details for your book prediction:")
# Author selection
author_input = input("\\n๐Ÿ‘ค Author name (from list above): ").strip()
if not author_input:
author_input = "Stephen King" # Default
# Ratings count
try:
ratings_input = input("๐Ÿ“Š Expected ratings count (e.g., 50000): ").strip()
ratings_count = int(ratings_input) if ratings_input else 50000
except ValueError:
ratings_count = 50000
# Reviews count
try:
reviews_input = input("๐Ÿ’ฌ Expected reviews count (optional): ").strip()
reviews_count = int(reviews_input) if reviews_input else None
except ValueError:
reviews_count = None
# Make prediction
print("\\n๐Ÿค” Analyzing book characteristics...")
result = predictor.predict_book_rating(author_input, ratings_count, reviews_count)
if "error" in result:
print(f"โŒ Error: {result['error']}")
else:
predicted_rating = result["predicted_rating"]
confidence = result["confidence"]
print(f"\\n๐ŸŽฏ PREDICTION RESULT:")
print(f" ๐Ÿ“– Book by: {author_input}")
print(f" โญ Predicted Rating: {predicted_rating}/5.0")
print(f" ๐ŸŽฏ Confidence: {confidence}")
if confidence == "High":
print(" โœ… High confidence prediction!")
elif confidence == "Medium":
print(" โš ๏ธ Medium confidence - consider more popular author")
else:
print(" ๐Ÿ”„ Low confidence - prediction may be less reliable")
except KeyboardInterrupt:
print("\\n\\n๐Ÿ‘‹ Demo ended by user.")
except Exception as e:
print(f"\\nโŒ Error during interactive prediction: {e}")
print("\\n" + "=" * 50)
print("๐Ÿš€ Want to try the web interface?")
print(" Run: streamlit run streamlit_app.py")
print(" Then visit: http://localhost:8501")
print("\\n๐Ÿ“š Thanks for trying Book Popularity Predictor!")
print("=" * 50)
if __name__ == "__main__":
run_demo()